0

I use the following code to pass an array to a function and print its size before and after calling the function:

#include <stdio.h>

int passing_array(int array[]) {
    int size = sizeof(array);
    printf("The size after passing: %d\n", size);
}

int main () {
    int a[] = {1, 2, 3};

    int size = sizeof(a);
    printf("The size before passing: %d\n", size);

    passing_array(a);

    return 0;
}

After running the code, I got a strange result:

The size before passing: 12

The size after passing: 8

My question is: why does the size of the array change from 12 to 8?

Community
  • 1
  • 1

2 Answers2

5
int passing_array(int array[]) {
    int size = sizeof(array);
    printf("The size after passing: %d\n", size);
}

is the same as

int passing_array(int* array) {
    int size = sizeof(array);
    printf("The size after passing: %d\n", size);
}

Hence, size is the size of a pointer.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

When you pass an array to a function, it decays to a pointer to the first element of the array. So int array[] in your parameter list is really int *array, and sizeof is returning the size of the pointer.

dbush
  • 205,898
  • 23
  • 218
  • 273