1

When I pass a char array through a method and use the sizeof method, it comes out different than if I were to use sizeof directly. Anybody know why and how I can fix this simple mistake?

#include <stdlib.h>

int main()
{
    char c[5];
    char car[] = { 'a', 'b', 'c' };;
    int num = my_strlen(c);

    printf("%d \n", sizeof(c));
    printf("%d \n", sizeof(car));

    printf("%d \n", my_strlen(c));
    printf("%d \n", my_strlen(car));


    return 0;
}

int my_strlen(char s[]) // returns number of characters in a string
{
    return sizeof(s);
}

Output:

5
3
8
8
Mercifies
  • 152
  • 1
  • 13
  • `printf("%d \n", sizeof(c));` and `printf("%d \n", sizeof(car));` invoke *undefined behavior* by passing data having wrong type to `printf()`. Format `%zu` should be used to print `size_t`, which is `sizeof`'s result. – MikeCAT May 12 '16 at 02:21
  • You should declare or define functions *before* using them. – MikeCAT May 12 '16 at 02:21
  • You can't pass an array into a function, and you aren't passing an array into a function here. – user253751 May 12 '16 at 02:22

1 Answers1

1

Arrays decay to pointers when used as arguments, this implies that

int my_strlen(char s[])
{
  return sizeof(s);
}

is instead

int my_strlen(char* s)
{
  return sizeof(s);
}

So sizeof(s) == sizeof(char*) == sizeof(void*) which apparently is 8 bytes on your machine because you are running on a 64 architecture.

Jack
  • 131,802
  • 30
  • 241
  • 343