繁体   English   中英

以下代码使用 arrays、指针等打印的内容

[英]What the following code prints / with arrays, pointers etc

我在解决这个问题时遇到了问题,所以如果有人有类似的问题,它会对我有很大帮助。

short y[2][3]={{0123},{0x12345}},*p=y[1];
printf("01:%x\n", y);
printf("02:%x\n", p);
printf("03:%x\n", sizeof(y));
printf("04:%x\n", sizeof(y[0]));
printf("05:%x\n", sizeof(&y[0]));
printf("06:%x\n", sizeof(*p));
printf("07:%x\n", sizeof(p++));
printf("08:%x\n", *p++);
printf("09:%x\n", *p);
return 0;

谁能给我解释一下为什么打印输出是这样的?

01:61ff10
02:61ff16
03:c
04:6
05:4
06:2
07:4
08:2345
09:0

我的想法:

01:Prints the address where the array y begins.
02:Prints the address of the pointer, which points to the second element of the array. Since we have 2 * 3 elements that are of type short, each subsequent element of the zero element will increase by 6.
03:Since we have 2 * 3 elements, which is equal to 6, but the elements of the type are short, so it will print hexadecimal c
04:the number of elements in the zero position is 3, but they are of the short type, so it prints 6
05:prints the sizeof addresses of the first element of the array which is 4
06:I don't know why it prints 2 here
07:Prints the sizeof of the pointer address which is 4, it will increase after printing
08:I do not understand
09:I do not understand

谁能解释为什么它打印成这样?

好吧,让我们来看看:

  • #01: y的地址。
  • #02: p的值,它包含y[1]的地址,它是short[3]类型的第二个元素。 在您的系统上, short的大小显然是 2,因此 #01 的偏移量是 6。
  • #03:数组y的大小, 2 * 3 * sizeof (short)给出 12,十六进制c
  • #04:元素y[0]的大小,类型为short[3] 6,如你所见。
  • #05: y[0]的地址大小,显然地址的大小在您的系统上是 4。
  • #06: p指向的object的大小。 这是一个short的,所以 2。
  • #07:表达式p++的大小,它是一个地址,所以是 4。不, p没有递增,因为表达式没有被计算。
  • #08: p指向的object的值,即y[1][0] 由于0x12345的初始值是一个太大而无法存储在short中的int ,因此它被截断为0x2345 读取值后, p递增。
  • #09: p指向的元素,即y[1][1] 它被初始化为 0。

笔记:

你应该从你的编译器那里得到警告:

  • 提到的初始值设定项被截断。
  • 指针/地址的格式是%p
  • sizeof结果的类型可能与格式%x不匹配。

你应该认真对待警告,它们总是暗示你很可能犯了错误。

N6) Sizeof(*p) 是 p 指向的数据类型的大小。 p 是指向 short 的指针:所以 2 个字节。

N8) p 是指向 short 的指针,它指向数组元素 y[1][0]。 y[1] 和 y[1][0] 具有相同的 memory 地址。

所有数组元素都很短,0x12345 在数组初始化时截断为 0x2345。 所以 output 是 2345。此外,p++ 增加指针值以指向下一个短 y[1][1]。

N9) 由于步骤 N8 中的 p++,指针现在指向 y[1][1],它被初始化为 0(默认情况下,因为未提供初始值)- output 为 0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM