使用malloc分配不同行长度的multidimensional array

我有以下的C代码:

 int *a; size_t size = 2000*sizeof(int); a = (int *) malloc(size); 

这工作正常。 但是,如果我有以下几点:

 char **b = malloc(2000*sizeof *b); 

b每个元素都有不同的长度。

如何为b做同样的事情,就像我为b做的一样; 即下面的代码将保持正确?

 char *c; size_t size = 2000*sizeof(char *); c = (char *) malloc(size); 

首先,你需要分配像char **c = malloc( N * sizeof( char* ))这样的指针数组,然后为每个行分配一个对malloc的单独调用,可能在循环中:

 /* N is the number of rows */ /* note: c is char** */ if (( c = malloc( N*sizeof( char* ))) == NULL ) { /* error */ } for ( i = 0; i < N; i++ ) { /* x_i here is the size of given row, no need to * multiply by sizeof( char ), it's always 1 */ if (( c[i] = malloc( x_i )) == NULL ) { /* error */ } /* probably init the row here */ } /* access matrix elements: c[i] give you a pointer * to the row array, c[i][j] indexes an element */ c[i][j] = 'a'; 

如果你知道元素的总数(例如N*M ),你可以在一个单独的分配中做到这一点。

dynamic分配typesT的N×M数组的典型forms是

 T **a = malloc(sizeof *a * N); if (a) { for (i = 0; i < N; i++) { a[i] = malloc(sizeof *a[i] * M); } } 

如果数组中的每个元素具有不同的长度,则用该元素的适当长度replaceM; 例如

 T **a = malloc(sizeof *a * N); if (a) { for (i = 0; i < N; i++) { a[i] = malloc(sizeof *a[i] * length_for_this_element); } } 

char a[10][20]等价内存分配如下。

 char **a; a=(char **) malloc(10*sizeof(char *)); for(i=0;i<10;i++) a[i]=(char *) malloc(20*sizeof(char)); 

我希望这看起来很容易理解。

另一种方法是分配一个连续的内存块,包括用于指向行的指针的头块以及用于存储实际数据的主体块。 然后,通过将正文中的内存地址分配给基于每行的头中的指针来标记内存。 它看起来如下所示:

 int** 2dAlloc(int rows, int* columns) { int header = rows * sizeof(int*); int body = 0; for(int i=0; i<rows; body+=columnSizes[i++]) { } body*=sizeof(int); int** rowptr = (int**)malloc(header + body); int* buf = (int*)(rowptr + rows); rowptr[0] = buf; int k; for(k = 1; k < rows; ++k) { rowptr[k] = rowptr[k-1] + columns[k-1]; } return rowptr; } int main() { // specifying column amount on per-row basis int columns[] = {1,2,3}; int rows = sizeof(columns)/sizeof(int); int** matrix = 2dAlloc(rows, &columns); // using allocated array for(int i = 0; i<rows; ++i) { for(int j = 0; j<columns[i]; ++j) { cout<<matrix[i][j]<<", "; } cout<<endl; } // now it is time to get rid of allocated // memory in only one call to "free" free matrix; } 

这种方法的优点是优雅的释放内存,并能够使用类似数组的符号来访问生成的二维数组的元素。

如果b中的每个元素都有不同的长度,那么你需要做如下的事情:

 int totalLength = 0; for_every_element_in_b { totalLength += length_of_this_b_in_bytes; } return (char **)malloc(totalLength); 

我认为2步法是最好的,因为c 2-d数组只是数组的数组。 第一步是分配一个单独的数组,然后遍历它为每列分配数组。 本文给出了很好的细节。

malloc不会在特定的边界上分配,所以必须假定它分配在一个字节边界上。

如果转换为任何其他types,则返回的指针可能无法使用,因为访问该指针可能会由CPU产生内存访问冲突,并且应用程序将立即closures。

二维arraysdynamic内存分配

 int **a,i; // for any number of rows & columns this will work a = (int **)malloc(rows*sizeof(int *)); for(i=0;i<rows;i++) *(a+i) = (int *)malloc(cols*sizeof(int));