这可接受的做法是在堆上初始化数组吗?

时间:2011-06-06 22:41:30

标签: ios

这是可接受的代码吗?:

unsigned char *buffer= malloc(16 * sizeof(*buffer));
        if (buffer == NULL) {
            errorText.text= @"Insufficient memory.";
            NSLog(@"%@",@"Insufficient memory.");
            return;
        }
        unsigned char temp[16]= {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
        memcpy(buffer,temp,16);
        NSData* seed= [NSData dataWithBytesNoCopy:buffer length:16];

或:

unsigned char *buffer= malloc(16 * sizeof(*buffer));
if (buffer == NULL) {
    errorText.text= @"Insufficient memory.";
    NSLog(@"%@",@"Insufficient memory.");
    return;
}
memset(buffer,0,16); // set all bytes to zero
buffer[0]= 0x01;
buffer[1]= 0x02;
buffer[2]= 0x03;
buffer[3]= 0x04;
buffer[4]= 0x05;
buffer[5]= 0x06;
buffer[6]= 0x07;
buffer[7]= 0x08;
buffer[8]= 0x09;
buffer[9]= 0x0a;
buffer[10]= 0x0b;
buffer[11]= 0x0c;
buffer[12]= 0x0d;
buffer[13]= 0x0e;
buffer[14]= 0x0f;
buffer[15]= 0x10;
NSData* seed= [NSData dataWithBytesNoCopy:buffer length:16];

我的C有点生锈!

1 个答案:

答案 0 :(得分:0)

[编辑删除有关不使用带有dataWithBytesNoCopy的malloc的虚假建议]

另一种选择是只使用-dataWithBytes:并让NSData为您处理复制:

    static unsigned char seedBytes[16]= {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
    NSData* seed= [NSData dataWithBytes:seedBytes length:16];