Objective c Obj c在方法之间向uint8\t数组添加字节?

Objective c Obj c在方法之间向uint8\t数组添加字节?,objective-c,bytearray,byte,Objective C,Bytearray,Byte,我遇到了一个奇怪的问题,objc向byuint8\t数组添加了一个额外的字节 以下是涉及的两种方法: ViewController.m - (void)viewDidLoad { // hexData = NSData object const uint8_t *hexBytes = [hexData bytes]; // header is first 3 bytes uint8_t headerBytes[] = {hexBytes[0],hexBytes[

我遇到了一个奇怪的问题,objc向byuint8\t数组添加了一个额外的字节

以下是涉及的两种方法:

ViewController.m

- (void)viewDidLoad {
    // hexData = NSData object
    const uint8_t *hexBytes = [hexData bytes];

    // header is first 3 bytes
    uint8_t headerBytes[] = {hexBytes[0],hexBytes[1],hexBytes[2]};

    // output the size
    NSLog(@"View did load header size: %lu", sizeof(headerBytes));

    // create a MessageHeader object
    MessageHeader *messageHeader = [[MessageHeader alloc] initWithBytes:headerBytes];
}
MessageHeader.h

- (id)initWithBytes:(uint8_t *)bytes {
    self = [super init];
    if(self != nil){
        NSLog(@"Message header init bytes size: %lu", sizeof(bytes));
        NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];
        self.bytes = bytes;
    }
    return self;
}
控制台输出

视图加载标题大小:3

消息头初始化字节大小:4

这很奇怪!将字节输出到屏幕显示,在没有明显原因的情况下,额外的字节已附加到数据中。如果
eef231
是输入,则
eef23150
是init方法中的输出。这个额外的字节似乎是随机的

我想知道它是否可能是
init
方法中
uint8\u t headerBytes[]
uint8\u t*字节之间的转换


如果有人有更多的信息,那就太好了。感谢
bytes
initWithBytes
中声明为
uint8\t*
,即指向
uint\t
的指针


就硬件而言,指针的大小为4字节。它与数组大小无关,数组大小在该方法中是未知的。

问题在于
initWithBytes:
sizeof(bytes)
提供指针变量的大小,32位体系结构上为4字节


无法在被调用函数中获取原始C数组的大小(在运行时C数组不携带大小信息)。您需要将大小作为附加参数传递。

sizeof
是一个编译时运算符,不会执行您认为它会执行的操作

uint8_t[]上的sizeof给出该数组的大小,即1字节*3个元素=3字节。它可以这样做,因为数组声明附加了隐式大小信息

uint8_t*上的sizeof提供指针的大小,在32位系统上为4字节

有关其功能的详细信息,请参见
sizeof


如果要传递数组的长度,一般惯例是传递额外的长度参数。因为您使用的是objective c,所以应该传递一个NSData,它可以包含一个数据数组及其大小。

对,这很有意义,谢谢。因此,下一个问题是,如何传递
uint8\t
数组而不是指针?还是我不能?啊,谢谢!有道理。有没有办法传递原始的C数组而不是指针?还是我做得对?