简体   繁体   English

我的C程序在运行函数中的循环之前结束

[英]My c program ends before it runs the loop in the function

Im trying to run my c code,This code keep ending as soon as i press the return button (new line): 我正在尝试运行我的C代码,只要按下返回按钮(新行),该代码就会一直结束:

realloc Way - press 1 linked List way - press 2 (or any other key): 1 重新分配方式-按1链接的列表方式-按2(或任何其他键):1

Enter chars and to finish push new line: Program ended with exit code: 0 输入字符并完成推送新行:程序结束于退出代码: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. 我正在使用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 ;
        }
    }

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" 记住"Single Quote for Single Character"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM