正确使用sizeof和Byte [] [英] Using sizeof Correctly with Byte[]

查看:92
本文介绍了正确使用sizeof和Byte []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点儿不高兴了,但是我有以下代码(实际代码当然有道理):

I'm sort of out of my depths here, but I have the following code (the real code actually has a point of course):

- (NSData*) dataTheseBytes:(Byte[]) bytes {
     return [NSData dataWithBytes:bytes length:sizeof(bytes)];
}

编译器警告为

数组函数参数上的Sizeof将返回'Byte *'的大小(又名 'unsigned char *')而不是'Byte []'

Sizeof on array function parameter will return size of 'Byte *' (aka 'unsigned char *') instead of 'Byte []'

如何消除此警告(或者,我对字节数组不了解什么?)

How can I eliminate this warning (or rather, what am I not understanding about my array of bytes)?

此外,为什么此代码不会发生错误?必须与方法签名有关...?

Additionally, why doesn't the error happen with this code? Must have something to do with the method signature...?

    Byte bytes[3] = { byte1, byte2, byte3 };
    NSData *retVal = [NSData dataWithBytes:bytes length:sizeof(bytes)];

推荐答案

当您将C数组作为方法或C函数参数传递时,它衰减"到指向基础类型的指针(即,实际上传递了Byte[]Byte *.)因此,所调用的方法/函数不知道数组中存在多少个元素.

When you pass a C array as a method or C function argument, it "decays" to a pointer to the underlying type (i.e. Byte[] is actually passed as Byte *.) So the called method/function has no idea how many elements are present in the array.

您还必须传递数组的长度,以便被调用的代码知道您想要的内容.这就是+[NSData dataWithBytes:length:]具有第二个参数的原因.

You must also pass the length of the array in order for the called code to know what you want. That's why +[NSData dataWithBytes:length:] has that second argument.

这篇关于正确使用sizeof和Byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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