1

I understand if you have an array, and you do sizeof, it gives you the number of bytes that block of memory occupies, but I have some confusion regarding the follow situation.

int mylen(const char *str) {
    return sizeof(str);
}

int main(void) {
    char str[] = "hello";

    printf("%d\n", sizeof(str)); // this gives 6
    printf("%d\n", mylen(str)); // this gives 8
}

I understand mylen is just returning the sizeof char pointer, therefore 8, but in that case, why the first one works? It this the subtle distinction between str and char *?

dex
  • 77
  • 4
  • 13
  • 2
    Didn't you answer your own question? `I understand if you have an array, and you do sizeof, it gives you the number of bytes that block of memory occupies` and `I understand mylen is just returning the sizeof char pointer, therefore 8`, which answers why the results are different. – tkausl Nov 10 '18 at 04:30
  • `char str[]` is not a pointer? `const char*` is. There. – DeiDei Nov 10 '18 at 04:30
  • @DeiDei `str` in `char str[] = "hello";` is an array of 6 `char`. – Swordfish Nov 10 '18 at 04:31
  • Given `const char *str`, just what do you expect `sizeof(str)` to return? – Andrew Henle Nov 10 '18 at 04:32
  • 3
    `printf("%d\n", sizeof(str));` has undefined behavior. `sizeof` yields a `size_t`, not an `int`. – melpomene Nov 10 '18 at 04:34
  • Thanks for all the comments and response, second link in duplicate area answers my question. – dex Nov 10 '18 at 05:09

1 Answers1

0

It is the same reason why in

char foo[6];
sizeof(foo);  // yields 6

and in

char *bar;
sizeof(bar);  // yields 8  (or in general: the size of a pointer on your system)

btw, since the result of the sizeof-operator is of type size_t, your mylen() should return size_t (defined in <stddef.h>) instead of int.

Also, if you want to printf() a size_t you'll have to use "%zu", not "%d".

For more detail you might want to read something on array-to-pointer decay: Why do arrays in C decay to pointers?

Swordfish
  • 12,971
  • 3
  • 21
  • 43