-1

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
Yuan Tian
  • 83
  • 9

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
  • 200,579
  • 13
  • 144
  • 260
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
  • 186,650
  • 20
  • 189
  • 240