-2

I'm trying to figure out the size of an array in C.

My first implementation was based off of the accepted answer to this question:

int size = sizeof(arr)/sizeof(arr[0]);

But that always gave me one. I tried just doing:

int size = sizeof(arr);

And this gives me 4 every time, regardless of the size of the array.

Here's a minimal example of the code I used.

void findSize(int arr[]) {
    int size = sizeof(arr);
    printf("%d\n",size);
}

int main(int argc, char** argv) {
    int arr[] = {4,6,9,2,6,3,7,2,5,1,2};
    findSize(arr);
}

Regardless of the array I use, this code always prints 4.

Why is it printing 4, and how do I find the actual size of the array?

Community
  • 1
  • 1
Anubian Noob
  • 13,426
  • 6
  • 53
  • 75

3 Answers3

2

Your:

void findSize(int arr[]) {

is equivalent to:

void findSize(int arr[3424]) {

which is the same as:

void findSize(int *arr) {

Thus sizeof(arr) inside findSize evaluates size of a pointer.

In C99 you are able to do this (read more about it here):

void findSize(int n, int arr[n]) {

but even in this case sizeof(arr) returns size of a pointer.

Why? Because of array variables automatically decay to pointers to their first elements.

Update: was wrong about arguments in C99, sizeof works correctly only for variable length arrays declared in body of a function. Thanks to @rslemos. And subscripts are there to correctly advance pointers of nested arrays, see example.

xaizek
  • 5,098
  • 1
  • 34
  • 60
  • very interesting your note on C99; I didn't know that possibility. But sizeof is lost even in this case: gcc 4.8.3 for `int size(int len, int arr[len]) { return sizeof arr; }` gives `movl $4, %eax; ret` (i686 target). – rslemos Jul 02 '14 at 19:45
  • @rslemos, you're right I got it wrong, thanks. I didn't actually use such subscripts in parameter lists in practice. `sizeof` works correctly for VLAs in functions body, not when they are passed to different function. I also added a link to GCC's documentation on VLA's. Subscripts are there to correctly advance pointers, [see](http://ideone.com/xEJH7u). – xaizek Jul 02 '14 at 20:16
1

When you pass an array to a function, it decays to a pointer to the first element in the array, and the sizeof operator only get the size of the pointer and not the array it points to.

If you want to pass the size of the array to the function, you have to pass it as an argument.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

The function just gets passed a pointer to the first element, not the entire array.

Thomas Padron-McCarthy
  • 27,232
  • 8
  • 51
  • 75