gpt4 book ai didi

c - 在 C 中打印数组时的奇怪行为?

转载 作者:太空宇宙 更新时间:2023-11-04 00:11:33 25 4
gpt4 key购买 nike

我正在尝试打印一个数组,但是我没有得到所需的输出,循环完成打印预定义数组后出现奇怪的数字。

代码是:

#include <stdio.h>    
int main(){
int intArray[11] = {1,2,8,12,-13,-15,20,99,32767,10,31};
int i=0;
for(i=0;i<sizeof(intArray);i++){
printf("%d\n",intArray[i]);
}
}

输出:

1
2
8
12
-13
-15
20
99
32767
10
31
11
1629976468
2674040
2665720
1627423265
1
2665616
-2147417856
1629976534
1629976468
2674040
0
1627423172
1629976532
0
1629110043
0
0
0
0
0
0
0
0
0
0
0
1629976538
0
1629956432
2674276
0
1627407935

最佳答案

for 循环中的中断条件是错误的!这会导致 index-out-of bound problem因为 i 超过了最大索引值 10 因为数组长度只是 11。循环中断条件应该是<数组长度( =11) 但不是 < 数组大小。sizeof(intArray) 的值等于 11 * sizeof(int) (= 44)。

要理解它,请阅读: sizeof Operator :

6.5.3.4 The sizeof operator, 1125:

When you apply the sizeof operator to an array type, the result is the total number of bytes in the array.

据此当sizeof应用于静态数组标识符的名称时(不是通过malloc()/calloc()分配的) ),结果是整个数组的大小(以字节为单位),而不仅仅是地址。这等于每个元素的大小乘以数组的长度。
换句话说:sizeof(intArray) = 11 * sizeof(int)(因为 intArray 长度为 11)。因此,假设如果sizeof(int) 是 4 字节,则 sizeof(intArray) 等于 44

下面的代码示例及其输出将帮助您进一步理解(阅读评论):

int main(){
int intArray[11] = {1, 2, 8, 12, -13, -15, 20, 99, 32767, 10, 31};
int i = 0;

printf("sizeof(intArray): %d\n",
sizeof(intArray) //1. Total size of array
);
printf("sizeof(intArray[0]): %d\n",
sizeof(intArray[0]) //2. Size of one element
);
printf("length: %d\n",
sizeof(intArray) / sizeof(intArray[0]) //3. Divide Size
);
return 0;
}

输出:

sizeof(intArray):  44    //1. Total size of array:  11 * 4 = 44
sizeof(intArray[0]): 4 //2. Size of one element: 4
length: 11 //3. Divide Size: 44 / 4 = 11

可以查看工作代码@ ideone ,注意:我假设 int 的大小是 4

现在请注意,sizeof(intArray)44,它大于数组的长度,因此条件错误,您有 Undefined behavior在运行时的代码中。要更正它,请替换:

for(i=0; i < sizeof(intArray); i++)
// ^--replace-----^
// wrong condition = 44

与:

for(i=0; i < sizeof(intArray) / sizeof(intArray[0]); i++)
// ^------------------------------------^
// condition Corrected = 11



为了计算数组的长度,我简单地将数组的总大小除以一个元素的大小,代码是:

sizeof(intArray) / sizeof(intArray[0])   // 44 / 4 = 11
^ ^
total size of size of first element
array

关于c - 在 C 中打印数组时的奇怪行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18009725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com