Reputation: 1533
Im trying to run my c code,This code keep ending as soon as i press the return button (new line):
realloc Way - press 1 linked List way - press 2 (or any other key): 1
Enter chars and to finish push new line: Program ended with exit code: 0
if i just copy the function to the main then i have no problems and it runs good. Am i missing something? Im using xcode. Thank you
int main()
{
int a;
printf ("\n realloc Way - press 1\n linked List way - press 2 (or any other key):\n");
scanf("%d", &a);
if(a=='1') reallocWay();
else linkedListWay();
return 0;
}
void reallocWay()
{
char *data,*temp;
data=malloc(sizeof(char));
char c; /* c is the current character */
int i; /* i is the counter */
printf ("\n Enter chars and to finish push new line:\n");
for (i=0;;i++) {
c=getchar(); /* put input character into c */
if (c== 'q') /* break from the loop on new line */
break;
data[i]=c; /* put the character into the data array */
temp=realloc(data,(i+2)*sizeof(char)); /* give the pointer some memory */
if ( temp != NULL ) {
data=temp;
} else {
free(data);
printf("Error allocating memory!\n");
return ;
}
}
Upvotes: 0
Views: 845
Reputation:
Problem is with
if(a=='1') // You are comparing with character insteda of int
reallocWay();
you have to compare like this
if(a==1) // Compare with integer.
reallocWay();
Remember "Single Quote for Single Character"
Upvotes: 3