我使用Shawn Chin在这里发布的方法生成连续的二维数组[1] [2]它工作得很好。从他的岗位连续二维数组的重新分配
简述:
char** allocate2Dchar(int count_x, int count_y) {
int i;
# allocate space for actual data
char *data = malloc(sizeof(char) * count_x * count_y);
# create array or pointers to first elem in each 2D row
char **ptr_array = malloc(sizeof(char*) * count_x);
for (i = 0; i < count_x; i++) {
ptr_array[i] = data + (i*count_y);
}
return ptr_array;
}
与以下免费功能:
void free2Dchar(char** ptr_array) {
if (!ptr_array) return;
if (ptr_array[0]) free(ptr_array[0]);
free(ptr_array);
}
这不是明摆着要我如何创建在任何尺寸等效再分配功能,虽然我只有兴趣在保持连续性的同时重新分配行数。增加列的数量将会很有趣,但可能相当困难。除了说“这很难!”之外,我还没有发现任何关于这个问题的直接讨论。[2]
当然这可以通过一个可怕的蛮力方法,将数据复制到一个新的1D数组(上面的数据)进行存储,重新分配一维数组,然后释放并重新生成指针(ptr_array)到用于新尺寸的行元素。但是,这对于行修改来说非常缓慢,因为有必要将内存需求至少增加一倍以便复制数据,而这对于更改列的数量确实非常糟糕。
这是用于更改行数的一种示例(对于更改列数将无法正常工作,因为指针的偏移对于数据而言是错误的)。我还没有完全测试这一点,但你的想法...
double **
reallocate_double_array (double **ptr_array, int count_row_old, int count_row_new, int count_col)
{
int i;
int old_size = count_row_old * count_col;
int new_size = count_row_new * count_col;
double *data = malloc (old_size * sizeof (double));
memcpy (&data[0], &ptr_array[0][0], old_size * sizeof (double));
data = realloc (data, new_size * sizeof (double));
free (ptr_array[0]);
free (ptr_array);
ptr_array = malloc (count_row_new, sizeof (double *));
for (i = 0; i < count_row_new; i++)
ptr_array[i] = data + (i * count_col);
return ptr_array;
}
此外,这种方法需要你知道以前的大小,这是很厉害的!
任何想法非常感谢。
[1] How can I allocate a 2D array using double pointers?
[2] http://www.eng.cam.ac.uk/help/tpl/languages/C/teaching_C/node52.html
非常感谢。这是正确的,并且运作良好。 – coastal 2011-03-04 20:05:13