将复合文字分配给数组指针会在相同的地点和时间给出预期的结果和垃圾吗?
#include <stdio.h>
int main(void) {
int a[5], *p, i;
p = a;
p = (int []){1, 2, 3, 4, 5};
for (i = 0; i < 5; i++, p++) {
printf("%d == %d\n", *p, a[i]);
}
return 0;
}
你瞧(YMMV):
$ gcc -O -Wall -Wextra -pedantic -std=c99 -o test test.c; ./test
1 == -1344503075
2 == 32767
3 == 4195733
4 == 0
5 == 15774429
通过指针算术打印数组表明它确实包含 1 到 5 的整数序列,但是再次打印通过 indeces 表示的假定相同的数组会产生未初始化的废话。为什么?
#include <stdio.h>
int main(void) {
int a[5], *p, i;
p = a;
p = (int []){1, 2, 3, 4, 5};
for (i = 0; i < 5; i++, p++) {
printf("%d == %d\n", *p, a[i]);
}
return 0;
}
Lo and behold (YMMV):
$ gcc -O -Wall -Wextra -pedantic -std=c99 -o test test.c; ./test
1 == -1344503075
2 == 32767
3 == 4195733
4 == 0
5 == 15774429
Printing the array through pointer arithmetic shows that it indeed holds an integer sequence of 1 to 5, yet printing again what is supposedly the same array expressed through indeces gives uninitialized crap. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您只分配给
p
,而不分配给a
,因此a
永远不会被初始化。You only assign to
p
, never toa
, soa
is never initialized.您永远不会初始化
a
的元素。对p
的两次赋值都改变了p
指向的位置;这两个赋值操作对a
或其元素没有任何作用。You never initialize
a
's elements. Both assignments top
change wherep
points; neither assignment does anything toa
or its elements.您将
a
的值分配给p
,然后立即使用另一个整数数组的值覆盖它。在printf("%d == %d\n", *p, a[i])
*p
和a[i]
中不再引用内存中的同一位置,并且a
保持未初始化状态(因此是垃圾)。You assign the value of
a
top
, and then immediately override it with the value of another array of ints. Inprintf("%d == %d\n", *p, a[i])
*p
anda[i]
no longer reference the same place in memory, anda
remains uninitialized (hence the garbage).您正在分配给数组指针,而不是将数据复制到数组。因此,您从一个来源获取数据,而从另一个来源获取垃圾。
You're assigning to an array pointer, you do not copy the data to array. So you get the data from one source and rubbish from the other.
您的代码相当于:
由于
a
未初始化,因此您会得到不可预测的值(事实上,读取这些变量也是未定义的行为)。Your code is equivalent to this:
Since
a
is uninitialized, you get unpredictable values (in fact it is undefined behaviour to even read those variables).