我尝试为包含字符串的表动态分配内存。
在我的例子中,我必须动态地使用它,因为我不知道程序将如何获得行和列。
这是我的两个函数的代码:
1.首先是只为表分配内存。
2.第二个应该释放所有分配的内存。
3.在主函数中,我为字符串分配内存并复制预定义字符串的一部分(它是伪代码,仅作为示例)
结果是“运行时错误” 我在代码中做错了什么?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *** buildOptions(int rows, int columns) {
int i=0;
printf("1...\n");
char ***options = (char ***)malloc(rows * sizeof(char **));
printf("2...\n");
for(i=0; i<rows; i++) {
printf("3...\n");
options[i] = (char **)malloc(columns * sizeof(char *));
printf("4...\n");
}
return options;
}
void freeOptions(char ****options, int rows, int columns) {
int i, j;
for(i=0; i<rows; i++) {
for(j=0; j<columns; j++) {
if(*options[i][j])
free(*options[i][j]);
}
if(*options[i]) {
free(*options[i]);
}
}
free(*options);
}
int main(void) {
int i, j, k;
char * str = "123456789abcdefghjkl\0";
char ***options = buildOptions(5, 3);
printf("Starting...\n");
for(i=0; i<5; i++) {
for(j=0; j<3; j++) {
options[i][j] = (char *)calloc((i+j+2)+1, sizeof(char));
strncpy(options[i][j], str, i+j+2);
}
}
for(i=0; i<5; i++) {
for(j=0; j<3; j++) {
printf(">>options[%d][%d]=%s<<\n", i,j, options[i][j]);
}
}
freeOptions(&options, 5, 3);
//here I want to check if the memory is freed
for(i=0; i<5; i++) {
for(j=0; j<3; j++) {
printf(">>options[%d][%d]=%s<<\n", i,j, options[i][j]);
}
}
return 0;
}
最佳答案
将freeOptions的声明改为
void freeOptions(char ***options, int rows, int columns)
调用
freeOptions(options, 5, 3);
并在 freeOptions 中调用 free() 以
free(options[i][j]);
关于C - 为包含字符串的表动态分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36592260/