-1

Making a C array size function. This is typically the standard convention for a C array size, and it works within the function in which the array was created, but it doesn't seem to work when put into another function. Why is this?

int size(char a[]) {
    return (int) (size_t) (sizeof(a)/ sizeof(char));
}

void test() {
    char a[] = {'a','b','c','d'};
    printf("%d\n", size(a));
    printf("%d\n", (int) (size_t) (sizeof(a)/ sizeof(char)));
}

int main() {
    test();
    return 0;
}

RESULT:

8       -> INCORRECT
4       -> CORRECT
Ryan Cocuzzo
  • 3,109
  • 7
  • 35
  • 64

1 Answers1

4

It's because arrays decays to pointers in many situations, including passing them to functions. It's impossible to retrieve the size of a passed array from inside the function. If you want the function to know the size, then you need to pass it separately somehow. Many standard library functions uses this approach.

If you're only looking for a quick way to get the size of an array, use this macro:

#define SIZE(x) (sizeof(x)/sizeof(x[0]))

Sidenote: sizeof(char) is ALWAYS - by definition - equal to 1, so it is quite pointless to write. Especially if you're going to multiply or divide with it.

klutt
  • 30,332
  • 17
  • 55
  • 95