开发者

sizeof on argument

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 approach I want to take is to use sizeof on the whole string then subtract accordingly depending on a certain uncommon token. Cuts some operations than simply counting through everything.

So yea, I tried using the dereferencing operator on the array(and pointer too, tried it) but I 开发者_C百科end up getting only the first array element.

How can I sizeof passed arguments. I suppose passing by value might work but I don't really know if that's at all possible with strings.


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).


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.


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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜