[英]My while loop in C replays one more time than it should before it ends
[英]My c program ends before it runs the loop in the function
我正在尝试运行我的C代码,只要按下返回按钮(新行),该代码就会一直结束:
重新分配方式-按1链接的列表方式-按2(或任何其他键):1
输入字符并完成推送新行:程序结束于退出代码:0
如果我只是将函数复制到主要,那么我没有问题,它运行良好。 我想念什么吗? 我正在使用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 ;
}
}
问题出在
if(a=='1') // You are comparing with character insteda of int
reallocWay();
你必须像这样比较
if(a==1) // Compare with integer.
reallocWay();
记住"Single Quote for Single Character"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.