sizeof论点 [英] sizeof on argument

查看:61
本文介绍了sizeof论点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使使用 int foo(char str []); ,它将接受初始化为字符串文字大小为sizeof的数组也不起作用.我被要求做类似strlen的事情,而我想采取的方法是在整个字符串上使用sizeof,然后根据某个不常见的标记相应地减去.除了简单地计算所有内容,还可以减少一些操作.

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.

如何对传递的参数进行sizeof.我想按值传递可能有用,但我真的不知道字符串是否完全可以实现.

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 []); 将接收一个初始化为字符串文字的数组

int foo(char str[]); will take in an array initialized to a string literal

不是那样的.这里的 char str [] char * str 相同.将数组类型用作参数类型时,会将其转换为相应的指针类型.

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.

如果在函数中需要指向数组的大小,则可以使用另一个参数自己传递大小,或者如果可能的话,则需要在函数中自行计算大小(例如,在使用C字符串的情况下,您可以轻松找到字符串的结尾.

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

这篇关于sizeof论点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆