简体   繁体   English

分配二维数组的一维并返回

[英]allocating one dimension of two dimensional array and return

I try to dynamically allocate one dimension of a two dimensional array. 我尝试动态分配二维数组的一维。 The array is declared as follows: 数组声明如下:

uint16_t coord[][2];

I only need to allocate the rows, the number of coordinates. 我只需要分配行数,坐标数。 Over google I found enough code to allocate both of the dimensions, starting from: 在Google上,我找到了足够的代码来分配这两个维度,从以下开始:

uint16_t **coord;

I am not sure if I can still declare the array as above. 我不确定是否仍可以声明上述数组。 Do I need to do: 我需要做:

uint16_t *coord[2]; 

or not? 或不?

I also need to return the array (the pointer to it) from the allocating function so other functions can access the array like this: 我还需要从分配函数返回数组(指向它的指针),以便其他函数可以像这样访问数组:

foo = coord[4][0];
bar = coord[4][1];

What's the correct way to return the allocated array? 返回分配的数组的正确方法是什么?

According to the clockwise/spiral rule , the following declaration: 根据顺时针/螺旋规则 ,以下声明:

uint16_t *coord[2];

is an array of two pointers, which seems to be not what you want. 是两个指针组成的数组,这似乎不是您想要的。 However you can use this instead: 但是,您可以改用以下方法:

uint16_t (*coord)[2];

You can allocate memory for it like this: 您可以像这样分配内存:

coord = malloc(num_entries * sizeof(uint16_t[2]));

Now you can access it as a normal multi-dimensional array: 现在,您可以将其作为普通的多维数组进行访问:

coord[0][0] = 1;
coord[0][1] = 2;
coord[1][0] = 3;
coord[1][1] = 4;

Your are mixing arrays and pointers, these are not the same. 您正在混合数组和指针,它们并不相同。

uint16_t coord[][2];

is an incomplete type, since you didn't define one dimension. 是不完整的类型,因为您没有定义一个尺寸。 You would fixe that dimension by using an initializer. 您可以使用初始化程序来修复该尺寸。 It seems that you are not really familiar with that concept, so better you'd warm up with a one dimensional one: 似乎您并不真正熟悉该概念,因此最好采用一维模型:

uint16_t line[] = { 1, 2, 3 };

would give it three elements. 会给它三个要素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM