好的,这是一个简单的程序代码我试图编写实现功能的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,该程序运行正常.
不要乱用逻辑.那么发生了什么?
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)