Search code examples
arrayscparameter-passingsizeof

C - passing array in function an get its size


I am a Python user for quite a time now and now try to get into C. While Python does a lot in background for me i now have to code in C in a much more 'BASIC' way. I like it,... but its hard.

The important part starts here

I really like the len() method in Python to get the length of an array. But in C it seems as if i have to look for the size (in bytes) of an array and divide it by the size (in bytes) of one element to get the length for the hole array. If there is a simple or a more common way i would like to here about it. However i want to understand why the following program prints me different sizes for my array 'a'.

#include <stdio.h>

void print_array(int a[]){
   printf("size of 'a' in the function is: %d\n", sizeof(a));
}

int main(void){
   int a[5] = {0, 2, 4, 8, 16};
   printf("size of 'a' before the function is: %d\n", sizeof(a));
   print_array(a);
   return 0;
}

The output is the following:

size of 'a' befor the function is: 20
size of 'a' in the function is: 8

At least i want to write a function that prints and array which i don´t know the length of. What how i understand, in C is only possible by looping truth it. This is the code i would add to the 'print_array' function. But it does it not how i aspected it to do because of the 'wrong' size.

int loop = sizeof(a)/sizeof(a[0]);
for(int i = 0; i <= loop; i++){
        printf("Array[%d] = %d\n", i, a[i]);
    }

Output (element 3 and 4 are missing):

Array[0] = 0
Array[1] = 2
Array[2] = 4

Thanks a lot for any explanation!


Solution

  • In C you must pass in not only the array, which decays to a pointer, but the size of the array as well. In C the common convention is (array, size):

    void print_array(int a[], size_t s) {
      for (size_t i = 0; i < s; ++i) {
        ... a[i] ...
      }
    }
    

    Where you call it like:

    print_array(a, 5);