在C中调整2D数组的大小 [英] Resizing 2D Arrays in C
问题描述
当前,我正在尝试使用此代码段在C中调整2D数组的大小
currently I am trying to resize a 2D Array in C using this code snippet
array = (int**) realloc(array, s * 2 * sizeof(int));
其中s是以行和列为单位的数组大小.但是,当尝试像这样访问数组的新区域时,
Where s is the size of the array in rows and colums. However, when trying to access the new areas of the array like this,
array[3][0] = x;
我只会遇到段错误.阵列的旧区域可以正常工作.我该如何解决这个问题?
I only get a segfault. The old areas of the array work fine. How can I solve this issue?
推荐答案
假设您将array
声明为
int **array;
并分配为
array = malloc( sizeof *array * ROWS );
if ( array )
{
for ( size_t i = 0; i < ROWS; i++ )
array[i] = malloc( sizeof *array[i] * COLS );
}
您最终想到的结构如下:
The structure you wind up with looks something like:
+---+ +---+ +---+
array: | | -----> | | array[0] ------> | | array[0][0]
+---+ +---+ +---+
... | | array[1] ---+ | | array[0][1]
+---+ | +---+
... | | | array[0][2]
| +---+
| ...
|
| +---+
+--> | | array[1][0]
+---+
| | array[1][1]
+---+
| | array[1][2]
+---+
...
如果要增加数组中行的数量,但将列大小保持不变,则可以执行类似的操作
If you want to increase the number of rows in the array but leave the column sizes the same, you'd do something like
int **tmp = realloc( array, sizeof *array * (ROWS + add_rows) );
if ( tmp )
{
array = tmp;
for ( size_t i = 0; i < add_rows; i++ )
{
array[ROWS + i] = malloc( sizeof *array[ROWS + i] * COLS );
}
}
如果您希望保持相同的行数但增加每行中的列数量,则可以执行以下操作
If you want to leave the number of rows the same but increase the number of columns in each row, you would do something like
for ( size_t i = 0; i < ROWS; i++ )
{
int *tmp = realloc( array[i], sizeof *array[i] * (COLS + add_cols) );
if ( tmp )
{
array[i] = tmp;
}
}
如果要减少数组中的行数,则需要先释放受影响的行:
If you want to reduce the number of rows in the array, you will need to free the affected rows first:
for ( size_t i = 1; i <= del_rows; i++ )
free( array[ROWS - i] );
int *tmp = realloc( array, ROWS - del_rows );
if ( tmp )
array = tmp;
如果要减少列数:
for ( size_t i = 0; i < ROWS: i++ )
{
int *tmp = realloc( array[i], sizeof *array[i] * (COLS - del_cols) );
if ( tmp )
array[i] = tmp;
}
从那里,您应该能够找出所需的任何组合.我强烈建议一次只做一维(也就是说,如果您想增加和列的行数,请先行 ,然后执行各列).
From there, you should be able to figure out any combinations you need. I strongly recommend doing only one dimension at a time (that is, if you want to increase the number of rows and columns, do the rows first, then do the columns).
您总是希望将realloc
的结果分配给一个临时变量;如果realloc
无法满足请求,它将返回NULL
,并且如果将其分配回原始变量,则将丢失对先前分配的内存的唯一引用,从而导致内存泄漏.
You always want to assign the result of realloc
to a temporary variable; if realloc
cannot satisfy the request, it will return NULL
, and if you assign it back to the original variable, you will lose your only reference to the memory that was previously allocated, leading to a memory leak.
这篇关于在C中调整2D数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!