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.
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();
}
}
I have the following code. It is running fine. But sometimes the del and ins functions are going into infinite loop but sometimes working fine. The readt function is working fine, still I have included it for your reference. What is the problem with my del and ins? Is there any memory leak?
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#include<math.h>
#include<unistd.h>
struct node
{ int info;
struct node *link;
};
typedef struct node m;
m *search(int,m*);
m *del(int,m*);
m *ins(int,int,m*);
int posof(int,m*);
int readt(m *t_c,char path[])
{ int t,szt=0;
FILE *tfile;
char ch;
char filename[]="/temp.txt";
strcat(path,filename);
tfile=fopen(path,"r");
if(tfile==NULL)
exit(0);
fseek(tfile, 0, SEEK_END);
szt = ftell(tfile);
fseek(tfile,0,SEEK_SET);
if(szt!=0)
{ while(1)
{ fscanf(tfile,"%d%c",&t,&ch);
t_c->info=t;
t_c->link=(m*)malloc(sizeof(m));
t_c=t_c->link;
if(ch==';')
break;
}
}
t_c->link=NULL;
//free(t_c);
fclose(tfile);
return 0;
}
m *search(int Noftarget,m *t_c)
{ int i,p1,p2;
srand(time(NULL));
for(i=0;i<100;i++)
{ p1=(1+rand()%(Noftarget));
p2=(1+rand()%(Noftarget));
t_c=del(p1,t_c);
t_c=ins(p1,p2,t_c);
break;
}
return t_c;
}
m *del(int target,m *t_h)
{ m *t_c;
int j=1,i;
t_c=t_h;
i=posof(target,t_h);
if(i==1)
{ t_c=t_c->link;
t_h=t_c;
}
else
{ while(j<i-1)
{ t_c=t_c->link;
j++;
}
t_c->link=t_c->link->link;
}
return t_h;
}
m *ins(int target,int position,m *t_h)
{ int j=0;
m *swaptarget,*t_c;
t_c=t_h;
swaptarget=(m*)malloc(sizeof(m));
swaptarget->info=target;
if(position==1)
{ swaptarget->link=t_c;
t_h=swaptarget;
}
else
{ while(j<position-2)
{ t_c=t_c->link;
j++;
}
swaptarget->link=t_c->link;
t_c->link=swaptarget;
}
free(swaptarget);
return t_h;
}
int posof(int p1,m *t_c)
{ int i=1,a=0;
while(t_c->link!=NULL)
{ if(p1==t_c->info)
{ a=i;
break;
}
t_c=t_c->link;
i++;
}
return a;
}
int main()
{ int Noftarget=8,j,r=1,count=0,noi,szd_n=0,i=0,sz;
char cwd[200];
m *t_h;
getcwd(cwd, sizeof(cwd));
t_h=(m*)malloc(sizeof(m));
readt(t_h,cwd);
t_h=search(Noftarget,t_h);
free(t_h);
return 0;
}
and the content of temp file is:
1,2,3,4,5,6,7,8;
The program contains memory leaks. Memory is allocating iteratively inside the while loop but only one pointer is removing at the end. Need to remove all allocations. And there is no need to free any pointer at the ins function rather del function needs the free operation of deleted pointer. The modified code is here:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#include<math.h>
#include<unistd.h>
struct node
{ int info;
struct node *link;
};
typedef struct node m;
m *search(int,m*);
m *del(int,m*);
m *ins(int,int,m*);
int posof(int,m*);
int readt(m *t_c,char path[])
{ int t,szt=0;
FILE *tfile;
char ch;
char filename[]="/temp.txt";
strcat(path,filename);
tfile=fopen(path,"r");
if(tfile==NULL)
exit(0);
fseek(tfile, 0, SEEK_END);
szt = ftell(tfile);
fseek(tfile,0,SEEK_SET);
if(szt!=0)
{ while(1)
{ fscanf(tfile,"%d%c",&t,&ch);
t_c->info=t;
t_c->link=(m*)malloc(sizeof(m));
//printf("%d ",t_c->info);
t_c=t_c->link;
if(ch==';')
break;
}
}
t_c->link=NULL;
//free(t_c);
fclose(tfile);
return 0;
}
m *search(int Noftarget,m *t_c)
{ int i,p1,p2;
srand(time(NULL));
for(i=0;i<100;i++)
{ p1=(1+rand()%(Noftarget));
p2=(1+rand()%(Noftarget));
t_c=del(p1,t_c);
t_c=ins(p1,p2,t_c);
break;
}
return t_c;
}
m *del(int target,m *t_h)
{ m *t_c;
int j=1,i;
t_c=t_h;
i=posof(target,t_h);
if(i==1)
{ free(t_c);
t_c=t_c->link;
t_h=t_c;
}
else
{ while(j<i-1)
{ t_c=t_c->link;
j++;
}
free(t_c->link);
t_c->link=t_c->link->link;
}
return t_h;
}
m *ins(int target,int position,m *t_h)
{ int j=0;
m *swaptarget,*t_c;
t_c=t_h;
swaptarget=(m*)malloc(sizeof(m));
swaptarget->info=target;
if(position==1)
{ swaptarget->link=t_c;
t_h=swaptarget;
}
else
{ while(j<position-2)
{ t_c=t_c->link;
j++;
}
swaptarget->link=t_c->link;
t_c->link=swaptarget;
}
return t_h;
}
int posof(int p1,m *t_c)
{ int i=1,a=0;
while(t_c->link!=NULL)
{ if(p1==t_c->info)
{ a=i;
break;
}
t_c=t_c->link;
i++;
}
return a;
}
int main()
{ int Noftarget=7,j,r=1,count=0,noi,szd_n=0,i=0,sz;
char cwd[200];
m *t_h;
getcwd(cwd, sizeof(cwd));
t_h=(m*)malloc(sizeof(m));
readt(t_h,cwd);
print_tsp(t_h);
t_h=search(Noftarget,t_h);
print_tsp(t_h);
while(t_h!=NULL)
{ free(t_h);
t_h=t_h->link;
}
return 0;
}
It is checked by valgrind and does not have any memory leak.
i have to code a calculator that does adding or multiplication to numbers with maximum digits of 30 .(maximum number of operands i can enter is 20).
and this is what i came up with (it is long):
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void Adding(int Result[31],int temp[30][31],int cnt)
{
int remainder,i,j,ResultsA[60]={0};
for(i=0;i<30;i++)
{
for(j=0;j<30;j++)
{
ResultsA[j]=(ResultsA[j]+temp[i][j])%10;
remainder=(ResultsA[j]+temp[i][j])/10;
ResultsA[j+1] += remainder;
if(ResultsA[30])
{
cnt++;
}
}
}
for(i=0;i<30;i++)
{
Result[i]=ResultsA[i];
}
for(i=0;i<30;i++)
{
for(j=0;j<30;j++)
{
temp[i][j]=0;
}
}
return;
}
void Mul(int num,int Results[31],int Num_int[30][31],int cnt)
{
int remainder=0,i,j,rows,x;
for(i=0;i<1;i++)
{
Results[i]=1;
}
int temp[30][31]={0};
for(rows=0;rows<num;rows++)
{
for(i=0;i<30;i++)
{
for(j=0;j<30;j++)
{
temp[i][i+j]=remainder+(Num_int[rows][j]*Results[i])%10;
remainder=(Num_int[rows][j]*Results[i])/10;
}
}
Adding(Results,temp,cnt);
}
return;
}
void Plus(int num,int Nums_int[30][31],int Results[31],int cnt)
{
int i,j,remainder,len=0;
for(i=0;i<num;i++)
{
for(j=0;j<30;j++)
{
Results[j]=(Results[j]+Nums_int[i][j])%10;
remainder=(Results[j]+Nums_int[i][j])/10;
Results[j+1]+=remainder;
if(Results[30])
cnt++;
}
}
return;
}
void str_to_int(int Nums_int[20][31],char Nums_str[20][31])
{
int length[20]={0},i,j;
for(i=0;i<20;i++)
{
for(j=19;0<=j;j--)
{
while(Nums_str[i][j]<48||57<Nums_str[i][j])
length[i]++;
}
}
for(i=0;i<20;i++)
{
for(j=0;j<length[i];j++)
{
Nums_int[i][length[i]-j]=Nums_str[i][j]-'0';
}
}
return;
}
void calcBig(char op, int operands[][31], int numOperands, int result[31],int cnt)
{
if (op=='+')
{
Plus(numOperands,operands,result,cnt);
}
if(op=='*')
{
Mul(numOperands,result,operands,cnt);
}
return;
}
int main()
{
int i,cnt=0,y;
char x;
char Nums_str[20][31]={0};
int num, Nums_int[30][31]={0};
int Results[31]={0};
printf("select operator:\n");
scanf("%c",&x);
printf("enter number of operands:\n");
scanf("%d",&num);
printf("enter numbers <seperated by new line>:\n");
for(i=0;i<num;i++)
{
scanf("%s",Nums_str[i]);
}
str_to_int(Nums_int,Nums_str);
calcBig(x,Nums_int,num,Results,cnt);
printf("result:\n");
if(cnt)
{
printf("overflow!");
}
else{
for(i=29;0<=i;i--)
{
while(Results==0)
{
y++;
}
}
for(i=y;0<=i;i--)
{
printf("%d",&Results[i]);
}
}
return 0;
}
Num_int is the 2d array containing numbers from user , num is the number of numbers entered by user.
Mul is function for multiplying numbers in Nums_int.
str_to_int converts the number recieved from user from string to int and reverse the order.
Plus is a function to add numbers in Nums_int.
Adding is function to add numbers that are the result of multiplying a number by ever digit of the other numbers (it gives the result of multiplying two numbers).
the problem is that when i run the code i get this:
select the operation:
*/+
select number of operands:
num
enter numbers:
//entering numbers
and after entering the numbers nothing happens and the program doesnt even end (no return 0). simply nothing happens after entering the numbers
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, ...).
I have implemented push pop and get minimum in O(1) complexity. I have seen many solutions in C++. This is an implementation in C itself. Is the following program correct?
#include <stdio.h>
#include <stdlib.h>
int stack[15],aux[15];
int top=-1,count=-1,aux_count=-1,temp_aux=-1;
void push_auxilary(int ele)
{
aux[++aux_count] = ele;
}
void push_stack(int ele)
{
stack[++top]=ele;
}
void push(int ele)
{
if(top < 0 && aux_count < 0)
{
push_auxilary(ele);
push_stack(ele);
}
else
{
if(ele > aux[aux_count])
{
push_auxilary(aux[aux_count]);
push_stack(ele);
}
else
{
push_stack(ele);
push_auxilary(ele);
}
}
}
int pop_stack()
{
return stack[top--];
}
int pop_auxilary()
{
return aux[aux_count--];
}
int pop()
{
int a = pop_stack();
pop_auxilary();
return a;
}
void display()
{
for (int i = top; i >= 0; i--)
{
printf("%d\n",stack[i]);
/* code */
}
}
int get_min()
{
return aux[aux_count];
}
int main(int argc, char const *argv[])
{
int i=0;
push(5);
push(9);
push(1);
push(6);
push(1);
push(54);
push(34);
push(9);
push(3);
push(4);
push(7);
push(12);
push(02);
printf("the %d\n",get_min() );
for (i = aux_count; i >= 0; i--)
{
printf("%d\n",aux[i]);
}
return 0;
}
Looks like it gets the job done in O(1) indeed. Algorithmic-ally correct, but terrible from code reusage point of view.