I have posted my 2 source files. I've been trying to find out whats wrong for the last 6 hours but I cannot find the solution to these errors:
1>Mainirk.obj : error LNK2019: unresolved external symbol "public: __thiscall pokemon::pokemon(int,int,int)" (??0pokemon##QAE#HHH#Z) referenced in function "void _cdecl `dynamic initializer for 'enemy''(void)" (??_Eenemy##YAXXZ)
1>C:\Users\Taylor\Documents\Visual Studio 2010\Projects\irkling\Debug\irkling.exe : fatal error LNK1120: 1 unresolved externals
Mainirk.cpp and stats.h
//mainirk.cpp:
#include <iostream>
#include <string>
#include <windows.h>
#include "include/irrKlang.h"
#include <conio.h>
#include "stats.h"
#pragma comment(lib, "irrKlang.lib")
using namespace std;
using namespace irrklang;
int choose();
void charmander1();
void bulbasaur1();
void squirtle1();
void yourpokemon();
void enemypokemon();
void battle();
void bchoice();
void aichoice();
int axisx;
int axisy;
void grid();
void events();
void attack();
void defend();
int x;
int y;
int z;
int m;
int n;
void win();
void lose();
void results();
void talk1();
void travel();
int walk;
void refresh();
void enemy1();
int achoice;
pokemon enemy(1,2,1);
pokemon charmander(25,3,25);
pokemon bulbasaur(20,4,20);
pokemon squirtle(30,2,30);
int main()
{
choose();
yourpokemon();
cout<<"\nPress any key to continue.";
_getch();
system("cls");
cout<<"********************************";
cout<<"\nEverything suddenly goes dark.\n";
cout<<"\n\nYou feel a dark presense enter the area.\n";
cout<<"Your rival Chuy walks in and challenges you to a battle...\n\n\n";
cout<<"................==\n";
cout<<".............../´¯/)\n\n";
cout<<"............/....//\n\n";
cout<<".........../....//\n\n";
cout<<"...../´¯/..../´¯<\n\n";
cout<<".././.../..../..../.|\n\n";
cout<<"(.(....(....(..../.)..)\n\n";
cout<<".<......(...(.....</.../\n\n";
cout<<"..<.................<\n\n";
cout<<"....<..............<\n\n";
cout<<"......<.............<\n\n";
cout<<"\n________________________________\n";
cout<<"Press any key to continue..\n\n";
ISoundEngine* se = createIrrKlangDevice();
se->play2D("Red.mp3");
_getch();
system("cls");
do
{
battle();
aichoice();
_getch();
system("cls");
}
while (y>0 && m>0);
cout<<"Battle Over\n";
results();
refresh();
_getch();
system("cls");
talk1();
_getch();
do
{
grid();
travel();
events();
system("cls");
}
while (axisx!=100);
return 0;
}
int choose()
{
cout<<"Choose your pokemon!!!\n\n";
cout<<"********************************\n\n";
cout<<" Charmander has "<<charmander.hp()<<" hp and "<<charmander.dmg()<<" damage.\n\n";
cout<<" Bulbasaur has "<<bulbasaur.hp()<<" hp and "<<bulbasaur.dmg()<<" damage.\n\n";
cout<<" Squirtle has "<<squirtle.hp()<<" hp and "<<squirtle.dmg()<<" damage.\n\n";
cout<<"--------------------------------\n\n";
cout<<"Type [a] to choose Charmander\n\n";
cout<<"Type [b] to choose Bulbasaur\n\n";
cout<<"Type [c] to choose Squirtle\n\n";
char answer;
cin>>answer;
if (answer == 'a'||answer == 'A')
{
answer = 'a';
}
if (answer == 'b'||answer == 'B')
{
answer = 'b';
}
if (answer == 'c'||answer == 'C')
{
answer = 'c';
}
switch (answer)
{
if (answer =='a')
{
case 'a': charmander1();
enemy = squirtle;
y= charmander.hp();
z= charmander.dmg();
x= charmander.bhp();
}
if (answer == 'b')
{
case 'b': bulbasaur1();
enemy = charmander;
y = bulbasaur.hp();
z = bulbasaur.dmg();
x= bulbasaur.bhp();
}
if (answer == 'c')
{
case 'c': squirtle1();
enemy = bulbasaur;
y = squirtle.hp();
z = squirtle.dmg();
x= squirtle.bhp();
}
}return 0;
}
void charmander1()
{
cout<<"You have chosen the Pokemon Charmander!!!\n";
cout<<"Charmander is a fire type!\n";
}
void bulbasaur1()
{
cout<<"You have chosen the Pokemon Bulbasaur!!!\n";
cout<<"Bulbasaur is a grass type!\n";
}
void squirtle1()
{
cout<<"You have chosen the Pokemon Squirtle!!!\n";
cout<<"Squirtle is a water type!\n";
}
void yourpokemon()
{
cout<<"HP is "<<y<<" and damage is "<<z;
}
void battle()
{
cout<<"\n\tStatus\t\t";
cout<<"\n-----------------------\n";
cout<<"Your Pokemon\tEnemy Pokemon\n";
cout<<"HP: "<<y<<"\t\tHP: "<<m<<"\n";
bchoice();
}
void bchoice()
{
cout<<"\n\nType 1 to attack or 2 to defend\n";
cin>>achoice;
if (achoice ==1)
{
attack();
}
else if (achoice ==2)
{
defend();
}
else
{
cout<<"Retype your choice"<<endl;
}
}
void attack()
{
m = m-z;
cout<<"\nYour Pokemon attacks!";
}
void defend()
{
cout<<"\nYour pokemon defends!";
}
void aichoice()
{
if (achoice ==1)
{
cout<<"\nThe enemy pokemon attacks!";
cout<<"\nPress any key to continue";
y = (y-n);
}
else if (achoice ==2)
{
cout<<"\nThe enemy pokemon defends!";
cout<<"\nPress any key to continue";
}
}
void win()
{
cout<<"You have won the battle!\n";
}
void lose()
{
cout<<"You have lose the battle!\n";
}
void results()
{
if (y>0 && m <= 0)
{
win();
}
else if (m>0 && y <= 0)
{
lose();
}
}
void talk1()
{
cout<<"These animals are merely pawns in a series that is about to unfold\n";
cout<<"If i were you, I would enjoy my last days alive\n";
cout<<"*Chuy walks away..*\n";
}
void travel()
{
cout<<"\nIt is time to travel\n";
cout<<"Type 1 to travel North\n";
cout<<"Type 2 to travel South\n";
cout<<"Type 3 to travel West\n";
cout<<"Type 4 to travel East\n";
cin>>walk;
if (walk ==1)
{
axisy++;
}
if (walk ==2)
{
axisy--;
}
if (walk ==3)
{
axisx--;
}
if (walk ==4)
{
axisx++;
}
}
void grid()
{
cout<< "location Coordinates: "<<axisx<<","<<axisy<<"\n";
}
void events()
{
if (axisx ==5 && axisy ==10)
{
battle();
}
}
void refresh()
{
m = enemy.bhp();
}
void enemy1()
{
m = enemy.hp();
n = enemy.dmg();
}
//stats.h
#include <iostream>
using namespace std;
class pokemon
{
int health, damage, basehp;
public:
pokemon (int,int,int);
int hp()
{
return (health);
}
int dmg()
{
return (damage);
}
int bhp()
{
return (basehp);
}
};
This is because you declared a constructor pokemon that takes 3 integer parameters, but did not provide its implementation. You could either provide it inline in the header
class pokemon
{
int health, damage, basehp;
public:
pokemon (int _health, int _damage, int _basehp)
: health(_health)
, damage(_damage)
, basehp(_basehp) {
}
// ...
};
or separately in the cpp file, like this:
pokemon::pokemon(int health, int damage, int basehp) {
// do your initialization here...
}
Related
This is a plane game function I wrote. I use a two-dimensional array to represent the game variables but The running result is abnormal, and * will jump suddenly.
And there will be two * , at the same time, and the plane also will stop
There should be no two * in the process of traversing the two-dimensional array. I tried to modify the position of * but I still couldn't.It's OK to run part of the code alone, but when you use the key operation, the program makes an error, but I don't know what's wrong
#include<stdio.h>
#include <windows.h>
#include<stdlib.h>
#include<conio.h>
#define enemynum 3
int element [20][30];
int position_x,position_y;
int enemy_x[enemynum],enemy_y[enemynum];
int score;
void gotoxy(int x, int y)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}
void HideCursor()
{
CONSOLE_CURSOR_INFO cursor_info = {1,0};
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void startup()
{ element[20][30]={0};
position_x=10;position_y=15;
element[position_x][position_y]=1;
for(int k=0;k<enemynum;k++)
{
enemy_x[k]=rand()%3;enemy_y[k]=rand()%20;
element[enemy_x[k]][enemy_y[k]]=3;
}
HideCursor();
}
This is an encapsulated pointer callback function. I don't think we need to consider the above functions
void show()
{ int i,j;
gotoxy(0,0);
for(i=0;i<20;i++)
{
for(j=0;j<30;j++)
{ if(element[i][j]==1)
{
printf("*");
}else if(element[i][j]==3)
{
printf("#");
}
else
printf(" ");
}
printf("\n");
}
}
void updatewhithout()
{
int i,j;
for(i=0;i<20;i++)
{
for(j=0;j<30;j++)
{
if(element[i][j]==2)
{
element[i][j]=0;
if(i>0)
element[i-1][j]=2;
}
}
} static int flag;
if(flag<20)
flag++;
if(flag==20)
{ for(int k=0;k<enemynum;k++)
{
if(enemy_x[k]==20)
{
enemy_x[k]=rand()%3;
enemy_y[k]=rand()%20;
}
element[enemy_x[k]][enemy_y[k]]=0;
enemy_x[k]++;
element[enemy_x[k]][enemy_y[k]]=3;
flag=0;
}
}
}
void updatewhith()
{ char ch;
if( kbhit())
ch=getch();
if(ch=='a')
{ element[position_x][position_y]=0;
position_y--;
element[position_x][position_y]=1;
}
if(ch=='d')
{ element[position_x][position_y]=0;
position_y++;
element[position_x][position_y]=1;
}
}
int main()
{startup();
while(1)
{show();
updatewhithout();
updatewhith();
}
}
This program must handle data that represents the products used in the factory. It is desired that the product represents the following characteristics: Code, description unit of measure, and price; In turn, if the product is imported you want to know the origin of the product, while if it is purchased in the square you want to know the name of the provider's phone number.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <stdbool.h>
#include <winsock.h>
void clrscr();
typedef enum {IMPORTED, LOCAL} type;
typedef struct
{
int code;
char description [20];
char MeasureUnit [5];
float price;
type discriminant;
union
{
char origin [20];
char destination [20];
int telephone;
} impoExpo;
} Product;
//this procedure fails
void loadProduct (Product *p)
{
printf("\nEnter the code:");
scanf("%d",&Product.code); //<-error: expected expression before 'Product'
fflush(stdin);
printf("\nEnter the description:");
scanf("%s",Product.description);
printf("Indicate the unit of measure:");
scanf("%s",Product.MeasureUnit);
printf("Enter the price:");
scanf("%f",&Product.price);
int i;
printf("\nInsert 1 if imported");
scanf("%d", &i);
if(i == 1)
{
p->discriminant = IMPORTED;
}
else
{
p->discriminant = LOCAL;
}
if(p->discriminant == IMPORTED)
{
printf("\nEnter source: ");
gets(p->impoExpo.origin);
}
else
{
printf("\nEnter the phone");
scanf("%d", &p->impoExpo.telephone);
}
}
//it is also
void showProduct (Product p)
{
printf("\nCode: %d", p.code); //<----- error: request for member 'code' in something not a structure or union
printf("\nDescription");
printf("%s", p.description);
printf("\nMeasurement unit:");
printf("%s", p.MeasureUnit);
printf("\nPrice:% .2f", p.price);
printf("\nType:");
if (p.discriminant == IMPORTED)
{
printf("Imported:");
printf("\nOrigin: %s", p.impoExpo.origin);
printf("%s", p.impoExpo.origin);
}
else
{
printf("Local:");
printf("\nTelephone: %d", p.impoExpo.telephone);
}
}
//this one also
bool areequal (Product p1, Product p2)
{
bool equal = false;
if ((p1.code == p2.code) && (p1.description == p2.description))
{
if ((p1.MeasureUnit == p2.MeasureUnit) && (p1.price == p2.price))
{
if (p1.discriminant == p2.discriminant)
{
if (p1.discriminant == IMPORTED)
{
if (p1.impoExpo.origin == p2.impoExpo.origin)
{
equal = true;
}
}
else
{
if (p1.impoExpo.telephone == p2.impoExpo.telephone)
{
equal = true;
}
}
}
}
}
return equal;
}
//this función ok
void copy (Product * const destination, const Product * const origin)
{
destination->code = origin->code;
(*destination->description) = (*origin->description);
(*destination->MeasureUnit) = (*origin->MeasureUnit);
destination->price = origin->price;
destination->discriminant = origin->discriminant;
if(destination->discriminant == IMPORTED)
(*destination->impoExpo.origin) = (*origin->impoExpo.origin);
else
destination->impoExpo.telephone = origin->impoExpo.telephone;
}
//and the latter also
int main ()
{
int option;
do
{
clrscr();
printf("Welcome to the program\n");
printf("Enter an option\n");
printf("1. Load a product\n");
printf("2. Show product\n");
printf("3. Check if two products are the same\n");
printf("0. Exit");
printf("Enter the option, and press ENTER");
scanf("%d",&option);
switch (option)
{
case 1:
loadProduct(&p);
getch();
break;
case 2:
showProduct(p);
getch();
break;
case 3:
printf("Enter the name of the product 1");
scanf("%d",&p1);
printf("Enter the name of the product 2");
scanf("%d",&p2);
printf("% d",areequal (p1, p2));
getch();
break;
}
} while (option != 0);
getch();
return 0;
}
void clrscr()
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord = {0, 0};
DWORD count;
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hStdOut, &csbi);
FillConsoleOutputCharacter(hStdOut, ' ', csbi.dwSize.X * csbi.dwSize.Y, coord, &count);
SetConsoleCursorPosition(hStdOut, coord);
}
Product is a pointer, so you have to access its members using the arrow notation:
scanf("%d",&p->code); //<-error: expected expression before 'Product'
C noob over here. Created a program that simulates a soccer team to help me get a handle on memory allocation. My program works but valgrind is telling me that I have a memory leak in the methods "create_player" and "add_player_to_club"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 8
typedef struct player {
int id;
char *position;
} Player;
typedef struct club {
int size;
Player *team[SIZE];
} Club;
Player *create_player(int id, const char *description);
void create_team(Club *club);
void print_club(const Club *club);
void destroy_player(Player *player);
void add_player_to_club(Club *club, int id, const char *position);
void destroy_club(Club *club);
int main() {
Club club;
create_team(&club);
add_player_to_club(&club, 1, "forward");
add_player_to_club(&club, 2, "goalie");
print_club(&club);
destroy_club(&club);
return 0;
}
Player *create_player(int id, const char *description){
Player *player;
player = malloc(sizeof(Player));
if(description == NULL){
player->position = NULL;
} else {
player->position = malloc(strlen(description) + 1);
strcpy(player->position, description);
player->id = id;
}
return player;
}
void destroy_player(Player *player){
if (player == NULL){
return;
} else {
free(player->position);
free(player);
}
}
void create_team(Club *team){
team->size = 0;
}
void print_club(const Club *club) {
int i = 0;
if (club == NULL) {
return;
} else if (club->size == 0) {
printf("No team members\n");
} else {
for (i = 0; i < club->size; i++) {
printf("Id: %d Position: %s\n", club->team[i]->id,
club->team[i]->position);
}
}
}
void add_player_to_club(Club *club, int id, const char *position){
if (club == NULL || club->size >= SIZE) {
return;
} else {
club->team[club->size] = create_player(id, position);
club->size++;
}
}
void destroy_club(Club *club){
int i = 0;
if (club == NULL) {
return;
} else {
club->size = 0;
for (i = 0; i < club->size; i++) {
destroy_player(club->team[i]);
}
}
}
I think the problem might be with my "destroy club" method. Player "objects" are stored in the "team" array. I allocated memory for each player object and deallocating by iterating through team array and freeing each index. What did I screw up?
In destroy_club, you set size to 0, then use that to loop through the players, so it loops through nothing.
Set size to 0 after cleaning up the players:
for (i = 0; i < club->size; i++) {
destroy_player(club->team[i]);
}
club->size = 0;
After i call printf for the first time to print out the duplicate it then changes it's mammals pointer to giberish. So when it prints inside the second loop the first mammal comes out fine but then the next in the list is lost. Then every time it exits that loop the next duplicate in the list is lost.
void print_list3() {
Duplicate *next=head3.duppointer;
int i,j;
for(i=0;i<list_length3;i++) {
printf("%c %d %f %f\n",next->species,next->number_of,next->location.lat,next->location.lng);
Mammal mam;
mam=*next->mampointer;
for(j=0;j<next->number_of;j++) {
printf(" %f %f %s\n",mam.location.lat,mam.location.lng,mam.observer.id);
if (mam.pointer!=NULL) {
mam=*mam.pointer;
}
}
if (next!=NULL) {
next=next->duppointer;
}
}
}
Edit: Decided to put all of my code in here, maybe it'll be easier for you guys to find the bug. The problem is with function 2.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "navigation.h"
#include "Mainheader.h"
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <math.h>
int list_length1=0;
int list_length2=0;
int list_length3=0;
Observer head1;
Mammal head2;
Duplicate head3;
/*
*
*/
int main(int argc, char** argv) {
int choice=0;
run_menu();
scanf("%d",&choice);
while(choice<1 || choice>4) {
printf("Invalid choice\n");
scanf("%d",&choice);
}
if(choice==1) {
function1();
}
else if(choice==2) {
function2();
}
else if(choice==3) {
function3();
}
else if(choice==4) {
printf("Exiting!");
}
return (EXIT_SUCCESS);
}
void run_menu() {
printf("1 - Display cetacean Mammals fn1\n"
"2 - Display without duplicates fn2\n"
"3 - Display Pods without duplicates fn3\n"
"4 - Exit\n");
}
void function1(){
int i=0;
get_directories();
Mammal *next;
next=head2.pointer;
for(i=0;i<list_length2;i++) {
location_calculator(next);
if (next!=NULL) {
next=next->pointer;
}
}
print_reallist();
}
void function2(){
int i=0;
get_directories();
Mammal *next;
next=head2.pointer;
for(i=0;i<list_length2;i++) {
location_calculator(next);
if (next!=NULL) {
next=next->pointer;
}
}
remove_duplicates();
print_list3();
}
void function3(){
}
char get_directories() {
char file1[256];
char file2[256];
char obsid[5];
TD td;
FILE *file_no1;
FILE *file_no2;
Observer* obs=malloc(sizeof(*obs));
Mammal* mam=malloc(sizeof(*mam));
//printf("Please Enter Observer File Path: ");
//scanf("%s",&file1);
strcpy(file1,"/ceri/homes1/j/jsc12/CS237/Assignment/cetaceans/data/observers_2.txt");
file_no1=fopen(file1, "r");
fscanf(file_no1,"%d%d%d%d%d%d",&td.day,&td.month,&td.year,&td.hour,&td.minute,&td.second);
while(fscanf(file_no1,"%s%lf%lf",obs->id,&obs->location.lat,&obs->location.lng)==3) {
obs->timedate=td;
Observer *new;
new=create_observer(obs->id,obs->location,obs->timedate);
add_observer(new);
}
fclose(file_no1);
//printf("Please Enter Sighting File Path: ");
//scanf("%s",&file2);
strcpy(file2,"/ceri/homes1/j/jsc12/CS237/Assignment/cetaceans/data/sightings_2.txt");
file_no2=fopen(file2, "r");
while(fscanf(file_no2,"%4s %c %lf%lf",&obsid,&mam->species,&mam->bearing,&mam->range)==4) {
Observer* obs2=find_observer(obsid);
mam->observer=*obs2;
Mammal *new;
new=create_mammal(mam->observer,mam->species,mam->bearing,mam->range);
add_mammal(new);
}
fclose(file_no2);
}
Mammal* create_mammal (Observer obs,char spec,double bear,double ran){
Mammal* b=malloc(sizeof *b);
b->observer=obs;
b->species=spec;
b->bearing=bear;
b->range=ran;
b->pointer=NULL;
return b;
}
void add_mammal (Mammal *n){
n->pointer=head2.pointer;
head2.pointer=n;
list_length2++;
}
Duplicate* create_duplicate (Duplicate* d){
Mammal mam;
int i;
location average;
average.lat=0;
average.lng=0;
mam=*d->mampointer;
Duplicate* b;
b=malloc(sizeof *b);
b->species=d->mampointer->species;
b->number_of=d->number_of;
for(i=0;i<d->number_of;i++) {
average.lat+=mam.location.lat;
average.lng+=mam.location.lng;
if (mam.pointer!=NULL) {
mam=*mam.pointer;
}
}
average.lat/=d->number_of;
average.lng/=d->number_of;
b->location=average;
b->mampointer=d->mampointer;
b->duppointer=NULL;
return b;
}
void add_duplicate (Duplicate *n){
n->duppointer=head3.duppointer;
head3.duppointer=n;
list_length3++;
}
Observer* create_observer (char id[5],location locat,TD timdat){
Observer* b=malloc(sizeof *b);
strcpy(b->id,id);
b->location=locat;
b->timedate=timdat;
b->pointer=NULL;
return b;
}
void add_observer (Observer *n){
n->pointer=head1.pointer;
head1.pointer=n;
list_length1++;
}
Observer* find_observer(char id[5]) {
Observer *next=head1.pointer;
int i=0;
while(i<list_length1) {
if(strcmp(id,next->id)==0) {
return(next);
}
next=next->pointer;
i++;
}
}
void location_calculator(Mammal* m) {
double obslat=m->observer.location.lat;
double obslng=m->observer.location.lng;
double rbear=(m->bearing*M_PI)/180;
m->location.lat=obslat+(m->range*cos(rbear))/60;
m->location.lng=obslng+(m->range*sin(rbear)/cos((obslat*M_PI)/180))/60;
}
void print_reallist() {
Mammal *next=head2.pointer;
int i;
printf("|==========|==========|==========|==========|\n");
printf("|%-10s|%-10s|%-10s|%-10s|\n","Longitude","Latitude","Species","Observer");
printf("|==========|==========|==========|==========|\n");
for(i=0;i<list_length2;i++) {
if (next->species=='P') {
printf("|%-10lf|%-10lf|%-10s|%-10s|\n",next->location.lat,next->location.lng,"Porpoise",next->observer.id);
if (next!=NULL) {
next=next->pointer;
}
}
else {
printf("|%-10lf|%-10lf|%-10s|%-10s|\n",next->location.lat,next->location.lng,"Dolphin",next->observer.id);
if (next!=NULL) {
next=next->pointer;
}
}
}
printf("|==========|==========|==========|==========|\n");
}
void remove_duplicates() {
int i,j;
double distance;
Mammal *next=head2.pointer;
for(i=0;i<list_length2-1;i++) {
Mammal *check=next->pointer;
Duplicate d;
d.mampointer=NULL;
d.number_of=0;
for(j=0;j<(list_length2-i)-1;j++) {
distance=great_circle(next->location, check->location);
if(distance<=0.02 && next->species==check->species) {
Mammal a=*next;
Mammal b=*check;
a.pointer=d.mampointer;
d.mampointer=&a;
b.pointer=d.mampointer;
d.mampointer=&b;
d.number_of++;
d.number_of++;
}
printf("%f\n",distance);
if (check!=NULL) {
check=check->pointer;
}
}
if(d.mampointer!=NULL) {
add_duplicate(create_duplicate(&d));
}
if (next!=NULL) {
next=next->pointer;
}
}
}
void print_list3() {
Duplicate *next=head3.duppointer;
int i,j;
for(i=0;i<list_length3;i++) {
printf("%c %d %f %f\n",next->species,next->number_of,next->location.lat,next->location.lng);
Mammal mam;
mam=*next->mampointer;
for(j=0;j<next->number_of;j++) {
printf(" %f %f %s\n",mam.location.lat,mam.location.lng,mam.observer.id);
if (mam.pointer!=NULL) {
mam=*mam.pointer;
}
}
if (next!=NULL) {
next=next->duppointer;
}
}
}
There are many problems for the first sight.
It is C, but would be better to avoid name 'new'. Identifier 'location' is a struct name and variable name too. Functions char get_directories() and Observer * find_observer() do not always return.
There are five malloc() but no free() calls.
I am afraid that such function declarations will not guarantee string size, a simple pointer is passed:
Observer * create_observer ( char id[5], ..
Return value of fscanf is not checked. 6 is expected but returns actually 1, because no proper format provided. Perhaps try "%2d%2d%2d%2d%2d%2d"!
fscanf(file_no1,"%d%d%d%d%d%d",&td.day,&td.month,&td.year,&td.hour,&td.minute,&td.second);
Same problem with observer lines. How should fscanf know where the end of string and/or double is? Try for instance "%4s %lf %lf"!
while(fscanf(file_no1,"%s%lf%lf",obs->id,&obs->location.lat,&obs->location.lng)==3) {
String obsid is not scanned properly at this point (remove address operator &):
while(fscanf(file_no2,"%4s %c %lf%lf",&obsid,&mam->species,&mam->bearing,&mam->range)==4) {
Function find_observer() would correctly return NULL if obsid not found. Pointer should not be used in this case, so please check obs2 first:
Observer* obs2=find_observer(obsid);
mam->observer=*obs2;
Could you provide code parts with example input to reproduce problem and resolve issue? I had to reverse engineer even to get following structures to compile at all:
struct Loc { double lat; double lng; };
struct TD { int year; int month; int day; int hour; int minute; int second; };
struct Observer { char id[1024]; Loc location; TD timedate; Observer * pointer; };
struct Mammal { char species; double bearing; double range; Observer observer; Mammal * pointer; Loc location; };
struct Duplicate { Mammal * mampointer; int number_of; char species; Loc location; Duplicate * duppointer; };
And great_circle( Loc, Loc ) function is missing either. Replaced by planar distance calculation instead of supposed spheric:
double great_circle( Loc p0, Loc p1 ) { return pow( ( p0.lat - p1.lat ), 2.0 ) + pow( ( p0.lng - p1.lng ), 2.0 ); }
Without trying duplicates it runs fine for me after fixing errors above.
When I run my program, it will print "Welcome to Blackjack! Rules: " and then an error window will come up saying "Blackjack.exe has stopped working and I have to close the program. In the compiler window it says "Process terminated". How do I stop this from happening?
Is one of the loops not working correctly?
My code:
#include <stdio.h>
#include <stdlib.h>
void Initializedeck(int[]);
void Shuffledeck(int[]);
void displayscore(int, int);
int hdrawcards(int[], int[]);
char getsuit(int);
int cdrawcards(int[], int[]);
int main()
{
int deck[52];
char cont;
int hcherries=10;
int ccherries=10;
int hcards[10];
int ccards[10];
int htotal;
int ctotal;
printf("Welcome to Blackjack!\n");
printf("Rules: \n ");
Initializedeck(deck);
cont='y';
while(cont=='y')
{
Shuffledeck(deck);
system("cls");
displayscore(hcherries, ccherries);
htotal=hdrawcards(hcards, deck);
ctotal=cdrawcards(ccards, deck);
if(htotal>ctotal)
{
printf("You Win!");
}
else
{
printf("Computer Wins. :( ");
}
printf("Do you want to continue?(y/n)");
scanf("%c", &cont);
}
return 0;
}
void Initializedeck(int deck[])
{
int i=0;
while(i<52)
{
deck[i]=i;
i++;
}
}
void Shuffledeck(int deck[])
{
int hold;
int max=51;
int random;
while(max>=0)
{
random=rand()%(max)+1;
hold=deck[max];
deck[max]=random;
random=hold;
max--;
}
}
void displayscore(int hcherries, int ccherries)
{
printf("Human: %i(cherries) Computer: %i(cherries)", hcherries, ccherries);
}
int hdrawcards(int hcards[], int deck[])
{
char answer;
int i=0;
int score=0;
int total=0;
char rank;
int worth;
char suit;
int card;
printf("Do you want to draw a card? (y/n)");
scanf("%c", &answer);
while(answer=='y' && total<21)
{
score=score+deck[i];
hcards[i]=deck[i];
card=hcards[i];
worth=hcards[i]%13;
if(worth==10)
{
rank='T';
}
else if (worth==11)
{
rank='J';
}
else if (worth==12)
{
rank='Q';
}
else if (worth==13)
{
rank='K';
}
else if(worth==1)
{
rank='A';
}
else
{
rank=worth;
}
if(worth>10)
{
worth=10;
}
total=total+worth;
suit=getsuit(card);
printf("%c%c\n", rank, suit);
printf("Total: %i", total);
i++;
scanf("%c", &answer);
}
return total;
}
int cdrawcards(int ccards[], int deck[])
{
int i=26;
int total;
int score;
int worth;
char rank;
char suit;
int card;
while(total<18)
{
score=score+deck[i];
ccards[i]=deck[i];
card=ccards[i];
worth=ccards[i]%13;
if(worth==10)
{
rank='T';
}
else if (worth==11)
{
rank='J';
}
else if (worth==12)
{
rank='Q';
}
else if (worth==13)
{
rank='K';
}
else if(worth==1)
{
rank='A';
}
else
{
rank=worth;
}
if(worth>10)
{
worth=10;
}
total=total+worth;
suit=getsuit(card);
printf(" %c%c\n", rank, suit);
printf(" Total: %i", total);
i++;
}
return total;
}
char getsuit(int card)
{
char suit;
if(card<13)
{
suit='S';
}
else if(card>=13 && card<26)
{
suit='H';
}
else if(card>=26 && card<39)
{
suit='D';
}
else if(card>=39 && card<52)
{
suit='C';
}
return suit;
}
You have an array overflow in cdrawcards():
int ccards[10];
...
ctotal = cdrawcards(ccards, deck);
...
int cdrawcards(int ccards[], int deck[])
{
int i = 26;
...
ccards[i] = deck[i]; //Overflow, ccards[] only has 10 elements
Either change the initial value of i or make the array larger int ccards[52]. I would also add an explicit check in cdrawcards() and hdrawcards() to ensure you don't overflow the arrays, like:
while (total < 18 && i < 10)
For example, in hdrawcards() you can overflow the array if you get a bunch of low value cards in a row (ex: 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3(overflow), 3, ...).