sizeof on argument

守給你的承諾、 提交于 2021-02-05 12:17:37

问题


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


回答1:


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




回答2:


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.




回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/7471929/sizeof-on-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!