动态分配二维数组,首先分配一维数组空间,也就是二维数组中的行;最后为每一行分配空间,也就二维数组中列。
注意最后释放内存。
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int row = 10; int col = 10; int i = 0; // 分配row行 char **data = (char **)malloc(sizeof(char *)*row); memset(data, 0, sizeof(char *)*row); for (i=0; i<row; i++) { // 为每一行分配col列 data[i] = (char *)malloc(sizeof(char)*col); memset(data[i], 0, sizeof(char)*col); } // 赋值测试 for (i=0; i<row; i++) { sprintf(data[i], "ABCDEFGH%d", i); } //输出测试 for (i=0; i<row; i++) { printf("%s\n", data[i]); } // 释放内存 for (i=0; i<row; i++) { free(data[i]); } free(data); return 0; }