Gilian Joosen
Gilian Joosen

Reputation: 486

c array size's change when used inside a function

I have this piece of code:

#include <stdio.h>

int max_number(int numbers_array[]);

int main(){
    int numbers_array[] = {10, 20, 30, 40, 50, 10, 60, 2500, 25555};
    printf("size: %d\n", sizeof(numbers_array));
    max_number(numbers_array);
    return 0;
 }

int max_number(int numbers_array[]){
    printf("size of array: %d\n", sizeof(numbers_array));
}

And the output is:

size: 36
size of array: 8

But the output should be the same right? Does anyone know what the problem is? Thank you very much.

Upvotes: 3

Views: 1396

Answers (3)

Pynchia
Pynchia

Reputation: 11606

Of course. The first is the size of the declared variable

int numbers_array[] = {10, 20, 30, 40, 50, 10, 60, 2500, 25555}

its size is well known even at compile time: 9 elements * 4 bytes each = 36 bytes

The second is the size of a pointer to an integer, 8 bytes (64 bits addressing)

The point is that the function has no way of knowing the size of its array parameter at any time. Since arrays are pointers, it will always and only see a pointer.

The following

int max_number(int numbers_array[])

is equivalent to

int max_number(int *numbers_array)

Upvotes: 2

Steephen
Steephen

Reputation: 15854

Array will decay to a pointer while using as a parameter to a function. So if you check the size of your array variable inside function, it will show the size of the pointer. So if you have a question, how you can find the size of the array, simplest answer is pass it as another variable to the function.

More info: http://c-faq.com/aryptr/aryptrparam.html

Upvotes: 1

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13196

No, it shouldn't. In main() where the array is declared, sizeof returns the size of the allocation: 36 bytes. Inside max_number, it has no idea how many bytes were allocated to the array since it was only passed a pointer, and sizeof just gives the size of the pointer (8 bytes).

Upvotes: 1

Related Questions