0

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 *numbers it prints the right size...?

Community
  • 1
  • 1
joels
  • 7,249
  • 11
  • 53
  • 94
  • 2
    Many duplicates on SO already, e.g. [Sizeof an array in the C programming language?](http://stackoverflow.com/questions/1975128/sizeof-an-array-in-the-c-programming-language) – Paul R Jul 04 '10 at 09:41

2 Answers2

8

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 :)

detly
  • 29,332
  • 18
  • 93
  • 152
1

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

Daniel Egeberg
  • 8,359
  • 31
  • 44
  • We need a "don't parse HTML with regex" equivalent for that assertion. – detly Jul 04 '10 at 09:46
  • @Neil Butterworth : "arrays" are not pointers, but it is true that the "array syntax" in C is just syntactic sugare for `*(ptr + index)` !! -1 if I could to the comment – ShinTakezou Jul 04 '10 at 14:04
  • Right. I would have thought it was obvious that I meant the array *syntax* when I was talking about something being "fancy syntax" for something else... – Daniel Egeberg Jul 04 '10 at 15:08
  • That completely fails to explain how the first part of their code works as they expected, but not the second. – detly Jul 05 '10 at 00:01