为什么我无法在代码中更改虚拟变量?

dar*_*rix 0 c

好的,这是一个简单的程序代码我试图编写实现功能的atoi功能.困扰我的是我无法更改块中的dummy变量,if而我可以更改n变量.n并且dummy在同一范围内定义.

int main()
{

    char *s;

    puts("Enter a string");
    fgets(s,100,stdin);
    int n = 0 , dummy = 1; // both are defined in the same scope 

    for(int i = 0 ; i < 2 ; i++ )
    {
        if(isdigit( s[i] ))    { n = n*10 + (s[i] - '0'); }

        if(1)
        {
            dummy = dummy + 99; // This is the thing not working , program stops executing
            // n = n + 99;  while this works fine
            printf("%d\n", dummy );
        }
    }
    printf("%d", n);
}
Run Code Online (Sandbox Code Playgroud)

我可以打印dummy变量罚款,但我无法为它分配一个值,当我试图做该程序停止工作.如果我评论涉及dummy和取消注释下面的行使用n,该程序运行正常.

不要乱用逻辑.那么发生了什么?

Sak*_*mar 5

char *s;
Run Code Online (Sandbox Code Playgroud)

s需要静态动态分配内存

char s[100];
Run Code Online (Sandbox Code Playgroud)

要么

char *s = NULL;
s = malloc(100);
if (s)
    /* do operations with s */
.
.
if (s)
    free(s);
Run Code Online (Sandbox Code Playgroud)

  • +1一个小点 - 在调用`free`之前你不需要测试`if(s)`.`free(NULL)`保证是安全的. (3认同)