开发者

int array size changes [duplicate]

开发者 https://www.devze.com 2023-01-05 10:54 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Sizeof an array in the C programming language?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Sizeof an array in the C programming language?

Why is the size of my int array changing when passed into a function?

I have this in my main:

int numbers[1];
numbers[0] = 1;
printf("numbers size %i", sizeof(numbers));
printSize(numbers);
return 0;

and this is the printSize method

void printSize(int numbers[]){
printf("numbers size %i", sizeof(numbers));}

You can see that I dont do anything else to the numbers array but the size changes when it gets to the printSize method...? If I use the value of *nu开发者_运维知识库mbers it prints the right size...?


Any array argument to a function will decay to a pointer to the first element of the array. So in actual fact, your function void printSize(int[]) effectively has the signature void printSize(int*). In full, it's equivalent to:

void printSize(int * numbers)
{
    printf("numbers size %i", sizeof(numbers));
}

Writing this way hopefully makes it a bit clearer that you are looking at the size of a pointer, and not the original array.

As usual, I recommend the C book's explanation of this :)


Well, you're just getting the size of the pointer to an int. Arrays are just fancy syntax for pointers and offsets.

0

精彩评论

暂无评论...
验证码 换一张
取 消