c - 关于打印阵列

标签 c arrays unions

我是 C 的新手。 假设我有一个 union 。

union DP 
{ 
  int c[3]; 
  char a[3][4]; 
  short b[2]; 
}point = {256,258,260}; 

printf("%i",point.a[0][1]); 
printf("%i",point.a[1][2]);
printf("%i",point.a[2][0]); 

为什么第一次打印给出 1,第二次打印为 0,第三次打印为 4?

最佳答案

您一次只能初始化union 的一个成员。 c 的元素(第一个成员)在此处初始化1ab 的成员未初始化。访问未初始化的变量会调用未定义的行为。您可能会得到预期或意外的结果。

n1570:附件 J:J.2 未定义行为

The behavior is undefined in the following circumstances:
...
— An lvalue designating an object of automatic storage duration that could have been declared with the register storage class is used in a context that requires the value of the designated object, but the object is uninitialized (6.3.2.1).


1:其他成员可以使用C99的designated initializers来初始化

关于c - 关于打印阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25163238/

相关文章:

c - 是否可以从静态库中删除死代码?

c - 使用 uint32_t 和 GCC 原子指令 union 32 位结构

c - 用 C 编写一个安全的标记 union

c - 在链表的末尾插入新节点 SEGV Error

c - 如何打印指向指针的指针

javascript - 存储包含 html 标签的文本

c - 如何打印数组中包含的结构元素

php - mysqli_fetch_array() foreach 循环重复

c++ - 使用 union 内部的结构体进行 Base64 编码

c - 在cuda设备函数中使用省略号