C语言 控制变量的位置对环体的影响



error

#include<stdio.h>
#include<string.h>
int main(void)
{
char *str = " H  el l  o, Wor   ld   ";
char del_space[256] = "";
printf("%sn",str);
for (size_t i = 0;str[i] != '';++i)
{
size_t j = 0;
if (str[i] != ' ')
{
del_space[j] = str[i];
++j;
}
}
printf("%s",del_space);
return 0;
}

正确

#include<stdio.h>
#include<string.h>
int main(void)
{
char *str = " H  el l  o, Wor   ld   ";
char del_space[256] = "";
printf("%sn",str);
for (size_t i = 0,j = 0;str[i] != '';++i)
{
if (str[i] != ' ')
{
del_space[j] = str[i];
++j;
}
}
printf("%s",del_space);
return 0;
}

为什么第一种方式是错误的,第二种方式是正确的?我刚刚移动了一个控制变量的位置,但第一种方式的del_space值是错误的?我使用的编译器是 GCC8.2.3 。这有什么特殊的原因吗?

第一个设置每次通过循环j = 0。第二个只设置j=0一次 - 第一次通过循环。

最新更新