gpt4 book ai didi

c - 为什么C中数组指针的大小总是8?

转载 作者:行者123 更新时间:2023-11-30 19:56:26 28 4
gpt4 key购买 nike

下面是比较数组本身的大小和数组指针的大小的简单代码。

#include <stdio.h>    
int main(){
int kkarray[100]= {1,0,};
int (*kkpointer) = kkarray;

printf("size of array using array itself : %ld \n" , sizeof(kkarray));
printf("size of array using pointer to array : %ld \n" , sizeof(kkpointer));
}

但结果是,

400
8

我可以理解第一个值是 400,但是第二个值,我认为它也应该是 400,因为当我分配一个指向数组的指针 kkpointer 时,它有点像数组的名称,它是 const地址值。例如,我可以使用 kkpointer[0] 获取数组的第一个值。我想知道为什么我得到的是“8”而不是 400。我不认为“8”是地址本身的大小。请告诉我。谢谢

最佳答案

任何指针的大小始终是 8 在您的平台上,因此它取决于平台。

sizeof 运算符不关心指针指向的位置,它给出指针的大小,在第一种情况下,它只给出数组的大小,而这不是数组的大小。一样。

这是引自§ 6.5.3.4¶ 2 N1570 草案

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant

§ 6.5.3.4¶ 4

When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1. When applied to an operand that has array type, the result is the total number of bytes in the array.103) When applied to an operand that has structure or union type, the result is the total number of bytes in such an object, including internal and trailing padding

如您所见,当应用于数组时,它给出了总字节数。但是如果你传递一个指针,那么结果将是它的类型的大小。

关于c - 为什么C中数组指针的大小总是8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27986044/

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