如何声明2D字节数组

时间:2021-10-17 20:58:18

I am trying to make a 2D byte array.

我正在尝试制作一个2D字节数组。

Can anybody give the code how to declare a NULL 2D byte array in Objective-C?

任何人都可以给代码如何在Objective-C中声明一个NULL 2D字节数组?

2 个解决方案

#1


Since objective-c is a strict superset of c, you could just use a pure c definition and it would work fine:

由于objective-c是c的严格超集,你可以使用纯c定义,它可以正常工作:

char** myMatrix = malloc(width*height);

You could also use an NSArray of NSArrays, but that's not a 2 dimensional array. It's a jagged array and considerably less easy to use than a plain byte array.

您也可以使用NSArray的NSArray,但这不是二维数组。它是一个锯齿状的数组,并且比普通的字节数组更不容易使用。

Another alternative is using an NSData/NSMutableData object. That is the Foundation way of working with byte arrays. See NSMutableData class reference for more information.

另一种方法是使用NSData / NSMutableData对象。这是使用字节数组的基础方法。有关更多信息,请参阅NSMutableData类参考。

NSMutableData* data = [NSMutableData dataWithLength:1024]; // One kilobyte
void* dataPointer = [data mutableBytes]; // Get a pointer to the raw bytes

#2


I'm cheating by doing this in C.

我在C中这样做是在作弊

size_t width;
size_t height;
unsigned char *twoDimArray = calloc(width*height);

#1


Since objective-c is a strict superset of c, you could just use a pure c definition and it would work fine:

由于objective-c是c的严格超集,你可以使用纯c定义,它可以正常工作:

char** myMatrix = malloc(width*height);

You could also use an NSArray of NSArrays, but that's not a 2 dimensional array. It's a jagged array and considerably less easy to use than a plain byte array.

您也可以使用NSArray的NSArray,但这不是二维数组。它是一个锯齿状的数组,并且比普通的字节数组更不容易使用。

Another alternative is using an NSData/NSMutableData object. That is the Foundation way of working with byte arrays. See NSMutableData class reference for more information.

另一种方法是使用NSData / NSMutableData对象。这是使用字节数组的基础方法。有关更多信息,请参阅NSMutableData类参考。

NSMutableData* data = [NSMutableData dataWithLength:1024]; // One kilobyte
void* dataPointer = [data mutableBytes]; // Get a pointer to the raw bytes

#2


I'm cheating by doing this in C.

我在C中这样做是在作弊

size_t width;
size_t height;
unsigned char *twoDimArray = calloc(width*height);