要使用 malloc 创建一个 char 数组,该数组可以使用 a[x][y] 作为二维数组访问,并且数据在内存中连续,可以这样做:
/* NOTE: only mildly tested. */
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;
}
请注意,返回的ptr_array 是指向行指针数组的指针。可以使用ptr_array[0] 引用实际数据的地址(第一行的第一列将是数据的开头)。
对于解除分配,ptr_array 上的普通 free() 是不够的,因为数据数组本身仍将继续运行。
/* free data array first, then pointer to rows */
void free2Dchar(char** ptr_array) {
if (!ptr_array) return;
if (ptr_array[0]) free(ptr_array[0]);
free(ptr_array);
}
示例用法:
#define ROWS 9
#define COLS 9
int main(int argc, char** argv) {
int i,j, counter = 0;
char **a2d = allocate2Dchar(ROWS, COLS);
/* assign values */
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
a2d[i][j] = (char)(33 + counter++);
}
}
/* print */
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%c ", a2d[i][j]);
}
printf("\n");
}
free2Dchar(a2d);
return 0;
}
上面的代码在起作用:
[me@home]$ gcc -Wall -pedantic main.c
[me@home]$ ./a.out
! " # $ % & ' ( )
* + , - . / 0 1 2
3 4 5 6 7 8 9 : ;
< = > ? @ A B C D
E F G H I J K L M
N O P Q R S T U V
W X Y Z [ \ ] ^ _
` a b c d e f g h
i j k l m n o p q