-5

I'm trying to use the trick to get the number of items in an array by dividing the array size by the size of the type: sizeof(array) / sizeof(<type>) or sizeof(array) / sizeof(array[0])

For reasons I don't fully understand, when I try to take an array as an argument to a function as type const char** and then call sizeof(), it always returns 8.

#include <stdio.h>

void write(const char** arr) {
    printf("%ld", sizeof(arr));
}

int main() {
    const char* word[] = {
        "asdf",
        "qwer",
        "hjkl"
    };

    write(word);

    return 0;
}
>> 8

So sizeof(array) / sizeof(const char*) always just comes out to 1.

What's going on?

JackHasaKeyboard
  • 1,599
  • 1
  • 16
  • 29
  • That `printf` doesn't generate that output. You should post something that actually compiles without warnings. See [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – user3386109 Apr 01 '18 at 00:51
  • Sorry about that, had to go out. – JackHasaKeyboard Apr 01 '18 at 04:16
  • 1
    When you pass an array to a function, the array decays to a pointer. So as far as the `write` function is concerned `arr` is a pointer, and `sizeof(arr)` is the size of a pointer. [Here's a link to a similar question.](https://stackoverflow.com/questions/24897716) – user3386109 Apr 01 '18 at 05:00

1 Answers1

1

Is that really your printf()? If so, it is totally wrong, you have no format string:

int main(void) {
    const char* word[] = {
        "asdf",
        "qwer",
        "hjkl"
    };


    printf("%zu\n", sizeof(word));
}

output :

12
Stephen Docy
  • 4,738
  • 7
  • 18
  • 31