【发布时间】:2016-09-10 14:23:11
【问题描述】:
我有这两个 c 编程代码。除了一步之外它们是相同的,因此它们的输出完全不同,请帮助我为什么会发生这种情况
main()
{
char ch[10]="123456";
char *p;
int a;
scanf("%d",&a);
p=ch+a;
*p='0';
printf("%s",ch);
}
output is
nik@debian:~$ ./a.out
4
123406
这里是另一个只有在第 [*p='0'] 行略有变化
main()
{
char ch[10]="123456";
char *p;
int a;
scanf("%d",&a);
p=ch+a;
*p=0; //only change is here rest is same
printf("%s",ch);
}
and output is
nik@debian:~$ ./a.out
4
1234
请帮我解释一下为什么它是不同的,因为我在 printf 中使用 %s 或其他我一直缺少的东西
【问题讨论】:
-
'0'!=0。 You may find this helpful -
注意:
p=ch+a;可能会调用 UB,如果输入的数字使指针指向数组之外。 -
假设我们暂时输入值
-
底层编码没有细微的变化。因为,每一点都很重要,它可能意味着“是”或“不是”。
标签: c arrays string pointers null-character