我试图运行我的c代码,只要按下返回按钮(新行),此代码就会一直结束:
realloc Way - 按1链接列表方式 - 按2(或任何其他键): 1
输入字符并完成推送新行:程序以退出结束 代码:0
如果我只是将函数复制到main,那么我没有问题,它运行良好。 我错过了什么吗? 我正在使用xcode。 谢谢
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 ;
}
}
答案 0 :(得分:3)
问题在于
if(a=='1') // You are comparing with character insteda of int
reallocWay();
你必须像这样比较
if(a==1) // Compare with integer.
reallocWay();
记住"Single Quote for Single Character"