【发布时间】:2011-04-15 11:26:45
【问题描述】:
我正在尝试创建一个指向 char 指针的指针,我可以轻松地向该指针添加新元素(字符串)。当我想添加新项目时,我使用 malloc 创建前 2 个维度和 realloc。我编写了有和没有 realloc 的代码,我得到了相同的结果。这是预期/正常的行为吗?
使用 realloc:
char **p; // create pointer to char pointer
p = malloc(sizeof(char*) * 2); // allocate 2 dimensions
p[0] = "ab";
p[1] = "cd";
void* resizedP = (void*)realloc(p, sizeof(char*) * 4); // resize array
p = (char**)resizedP;
p[2] = "ef";
p[3] = "gh";
printf("%s \n", p[0]); // prints ab
printf("%s \n", p[1]); // prints cd
printf("%s \n", p[2]); // prints ef
printf("%s \n", p[3]); // prints gh
free(p);
没有重新分配:
char **p;
p = malloc(sizeof(char*) * 2);
p[0] = "ab";
p[1] = "cd";
p[2] = "ef";
p[3] = "gh";
printf("%s \n", p[0]); // prints ab
printf("%s \n", p[1]); // prints cd
printf("%s \n", p[2]); // prints ef
printf("%s \n", p[3]); // prints gh
free(p);
【问题讨论】:
-
哦!我太想要一个无限的记忆库了!