Even with int foo(char str[]);
which will take in an array initialized to a string literal sizeof doesn\'t work. I was asked to do something like strlen and the app
You cannot pass an array as a function parameter, so you can't use the sizeof
trick within the function. Array expressions are implicitly converted to pointer values in most contexts, including function calls. In the context of a function parameter declaration, T a[]
and T a[N]
are synonymous with T *
.
You'll need to pass the array size as a separate parameter.
int foo(char str[]);
will take in an array initialized to a string literal
That's not what that does. char str[]
here is identical to char* str
. When an array type is used as the type of a parameter, it is converted to its corresponding pointer type.
If you need the size of a pointed-to array in a function, you either need to pass the size yourself, using another parameter, or you need to compute it yourself in the function, if doing so is possible (e.g., in your scenario with a C string, you can easily find the end of the string).
C strings are just arrays of char
. Arrays are not passed by value in C; instead, a pointer to their first element is passed.
So these two are the same:
void foo(char blah[]) { ... }
void foo(char *blah) { ... }
and these two are the same:
char str[] = "Hello";
foo(str);
char *p = str;
foo(p);
You can't use sizeof
here. In C arrays are decayed to pointers when passed to functions, so sizeof
gives you 4
or 8
- size of pointer depending on platform. Use strlen(3)
as suggested, or pass size of the array as explicit second argument.