C 指针和数组/“sizeof"运算符 [英] C pointers and arrays/ 'sizeof' operator
问题描述
可能的重复:char指针和数组的栈指针区别
为了说明我的问题:
int main(void){
int myary[20];
int *myaryPtr;
myaryPtr = myary;
sizeof(myary); // Will it return 80? Correct?
sizeof(myaryPtr); // Will it return 4? Correct?
return 0;
}
首先,我的假设是否正确?
First off, is my assumption correct?
然后假设我的假设是正确的,详细的解释是什么?我知道我的 20 元素数组是 80 个字节,但是名称 myary
不只是指向数组第一个元素的指针吗?所以不应该也是4吗?
And then assuming my assumption is correct, what is the detailed explanation? I understand that my 20 element array is 80 bytes, but isn't the name myary
merely a pointer to the first element of the array? So shouldn't it also be 4?
推荐答案
是的,您的假设是正确的,假设 int
和指针在您的机器上都是 4 个字节长.
Yes, your assumption is correct, assuming an int
and a pointer are both 4 bytes long on your machine.
不,数组不是指针.数组名称有时会在某些上下文中衰减为指针,但它们不是一回事.有一个 comp.lang.c 常见问题解答的整个部分专门针对这个共同点混乱.
And no, arrays aren't pointers. The array name sometimes decays into a pointer in certain contexts, but they aren't the same thing. There is a whole section of the comp.lang.c FAQ dedicated to this common point of confusion.
这篇关于C 指针和数组/“sizeof"运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!