-2

I have the following code in c:

void getNumber(int numberArray[])
{
    printf("The size of the array is %u", sizeof(numberArray));
}

void main()
{
    int array[6] = {1,2,3,4,5,6};
    getNumber(array);
}

but why the The size of the array is 4? And how to get the size of whole array?

user2131316
  • 3,111
  • 12
  • 39
  • 53
  • 5
    Aren't there literally thousands of duplicates of this? Did you spend *any* time looking for similar questions? – Kerrek SB Oct 04 '13 at 15:53

3 Answers3

3
void getNumber(int numberArray[])

is equivalent to

void getNumber(int* numberArray)

so sizeof(numberArray) is just measuring the size of int*.

If you want to know the length of the array, you either need to pass its length as a separate argument

void getNumber(int* numberArray, int len)

getNumber(array, sizeof(array)/sizeof(array[0]));

or arrange for the array to end with a known sentinel value

int array[] = {1,2,3,4,5,6,-1}; // assumes -1 is not a valid value

int arrayLength(int* numberArray)
{
    int len=0;
    while (*numberArray++ != -1) {
        len++;
    }
    return len;
}
simonc
  • 41,632
  • 12
  • 85
  • 103
1

This is not possible, except if you're using C99 and the array is a variable-length array.

In general an array is very much like a pointer in C, and even more so when being passed to a function.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

In case of getnumber(array) your array name array decays to pointer and is giving its size 4. In case of sizeof, an array name doesn't decays to pointer and hence giving the size of entire array.

haccks
  • 104,019
  • 25
  • 176
  • 264