2D char数组的动态内存

我已经声明了一个数组char ** arr; 如何初始化2D char数组的内存。

一种方法是执行以下操作:

char **arr = (char**) calloc(num_elements, sizeof(char*)); for ( i = 0; i < num_elements; i++ ) { arr[i] = (char*) calloc(num_elements_sub, sizeof(char)); } 

很清楚这里发生了什么 - 首先,你正在初始化一个指针数组,然后对于这个数组中的每个指针,你要分配一个字符数组。

你可以将它包装在一个函数中。 在使用之后你也需要释放()它们,如下所示:

 for ( i = 0; i < num_elements; i++ ) { free(arr[i]); } free(arr); 

我认为这是最简单的方法,可以满足您的需求。

分配char **类型的数组有两个选项

我已经从comp.lang.c FAQ中转录了这两个代码示例(其中也包含了这两种数组类型的一个很好的例证)

选项1每行一个分配加一个行指针。

 char **array1 = malloc(nrows * sizeof(char *)); // Allocate row pointers for(i = 0; i < nrows; i++) array1[i] = malloc(ncolumns * sizeof(char)); // Allocate each row separately 

选项2 - 将所有元素分配在一起并分配行指针:

 char **array2 = malloc(nrows * sizeof(char *)); // Allocate the row pointers array2[0] = malloc(nrows * ncolumns * sizeof(char)); // Allocate all the elements for(i = 1; i < nrows; i++) array2[i] = array2[0] + i * ncolumns; 

您也可以只分配一个内存块,并使用一些算术来获取元素[i,j] 。 但是你会使用char*而不是char**并且代码变得复杂。 例如arr[3*ncolumns + 2]而不是arr[3][2]

使用一维数组可能会更好:

 char *arr = calloc(WIDTH*HEIGHT, sizeof(arr[0])); for (int y=0; y 

使用以下技巧:

 typedef char char2D[1][1]; char2D *ptr; ptr = malloc(rows * columns, sizeof(char)); for(i = 0; i < rows; i++) for(j = 0; j < columns; j++) (*ptr)[i][j] = char_value; 
 char **array; int row,column; char temp='A'; printf("enter the row"); scanf("%d",&row); printf("enter the column"); scanf("%d",&column); array=(char **)malloc(row*sizeof(char *)); for (int i=0;i 

通过2D char数组,如果你的意思是字符串矩阵,那么它可以通过以下方式完成。

 int nChars = 25; // assuming a max length of 25 chars per string int nRows = 4; int nCols = 6; char *** arr = malloc(nRows * sizeof(char **)); int i; int j; for(i = 0; i < nCols; ++i) { arr[i] = malloc(nCols * sizeof(char *)); } for(i = 0; i < nRows; ++i) { for(j = 0; j < nCols; ++j) { arr[i][j] = malloc(nChars * sizeof(char)); sprintf(arr[i][j], "Row %d Col %d", i, j); } } 

打印2D char数组(字符串矩阵(char数组))

 for(i = 0; i < nRows; ++i) { for(j = 0; j < nCols; ++j) { printf("%s ", arr[i][j]); } printf("\n"); } 

结果是

 Row 0 Col 0 Row 0 Col 1 Row 0 Col 2 Row 0 Col 3 Row 0 Col 4 Row 0 Col 5 Row 1 Col 0 Row 1 Col 1 Row 1 Col 2 Row 1 Col 3 Row 1 Col 4 Row 1 Col 5 Row 2 Col 0 Row 2 Col 1 Row 2 Col 2 Row 2 Col 3 Row 2 Col 4 Row 2 Col 5 Row 3 Col 0 Row 3 Col 1 Row 3 Col 2 Row 3 Col 3 Row 3 Col 4 Row 3 Col 5