0
    #include <stdio.h>

    size_t arrSize(int a[])
    {
        return sizeof(a)/sizeof(a[0]);
    }


    int main()
    {
        int alfa[]={1, 2, 3, 4};
        size_t s= arrSize(alfa);
        printf("\n Array size: %zu", s);

        return 0;
    }

I'd like to know what I've done wrong here. The output is 2 when it should be 4 instead

I've tried including <stddef.h> but the problem still persists. The correct output comes only when I don't create a separate func and write size_t s=sizeof(a)/sizeof(a[0]) instead.

  • 1
    In the function you the array decays to a pointer. Your code divides the size of a pointer by the size of an element the pointer is pointing to. See https://stackoverflow.com/q/492384/10622916 – Bodo Aug 14 '23 at 17:04
  • Welcome! There may be a lot of duplicate question about this, but `sizeof(a)` is the size of a pointer. In C arrays do not get passed to functions, they decay to a pointer to the first element. A pointer contains no information about the size of its object: you must past the array length explicitly (unless there is a sentinel end value, such as a C string has). – Weather Vane Aug 14 '23 at 17:04
  • `int a[]`, as parameter, is just another way of writing `int *a`. You can't pass arrays to functions just pointers. – ikegami Aug 14 '23 at 17:33
  • and even if it *were* an array the `int a[]` would convey no size information anyway. When you do specify the number of elements, such as `size_t arrSize(int a[42])` the `42` will be completely ignored. The dimension is only needed for the inner dimension(s) of a multi-dimensional array, so that the compiler knows how to index it from the pointer that arrives. – Weather Vane Aug 14 '23 at 17:44

0 Answers0