所以,这是我的逻辑:
这是一些文字:
char *text;
然后这是文本数组:
char **arr;
那么这些数组的数组是:
char ***arr2d;
如果我想要一个函数来修改它,它需要接受它:
char ****arr2d;
并在函数内将其用作:
*arr2d = (e.g. allocate);
因此,如果我想创建这样的二维数组并使第一行、第一列仅包含一个字母“a”,那么为什么这不起作用?
#define COLUMNS 7
void loadTable(char ****table)
{
*table = (char ***) malloc(sizeof(char**));
if (!*table) {
printf("Allocation error for table rows.");
return;
}
*table[0] = (char**) malloc(COLUMNS * sizeof(char*));
if (!*table[0]) {
printf("Allocation error for table columns.");
return;
}
*table[0][0] = (char*) malloc(2 * sizeof(char));
*table[0][0][0] = (char)(97);
*table[0][0][1] = '\0';
}
int main()
{
char ***table;
loadTable(&table);
return 0;
}
最佳答案
您只需要 3 个 ***
即可执行您描述的操作,而不是 4 个 ****
。请注意,有一些方法可以让您避免字符串数组的数组深度过大。也有充分的理由避免数组的顺序过深,尤其是需要free(.)
你分配的所有东西。这意味着对 [m][c][re]alloc(.)
的每次调用恰好调用一次 free(.)
。
但是为了解决你的问题......
一般来说,要为以前分配的内存的单个数组创建新内存,您可以使用原型(prototype)如下的函数:
char * ReSizeBuffer(char **str, size_t origSize);
如果说先前分配的缓冲区创建为:
char *buf = calloc(origSize, 1);
...用法可能如下所示:
char *tmp = {0};
tmp = ReSizeBuffer(&buf, newSize); //see implementation below
if(!tmp)
{
free(buf);
return NULL;
}
buf = tmp;
///use new buf
...
然后,如果这适用于单个 char 数组,那么为先前分配的 array 字符串分配新内存的原型(prototype)可能如下所示:
char ** ReSizeBuffer(char ***str, size_t numArrays, size_t strLens);
假设先前分配的 2D 缓冲区创建为:
char **buf = Create2DStr(size_t numStrings, size_t maxStrLen); //see implementation below
...用法可能如下所示:
char **tmp = {0};
tmp = ReSizeBuffer(&buf, numStrings, maxStrLen);
if(!tmp)
{
free(buf);
return NULL;
}
buf = tmp;
///use new buf
...
实现:
ReSizeBuffer
的实现。如果您希望实现第二个原型(prototype),则必须对其进行扩展:
char * ReSizeBuffer(char **str, size_t size)
{
char *tmp={0};
if(!(*str)) return NULL;
if(size == 0)
{
free(*str);
return NULL;
}
tmp = (char *)realloc((char *)(*str), size);
if(!tmp)
{
free(*str);
return NULL;
}
*str = tmp;
return *str;
}
Create2DStr
的实现可能如下所示:
char ** Create2DStr(size_t numStrings, size_t maxStrLen)
{
int i;
char **a = {0};
a = calloc(numStrings, sizeof(char *));
for(i=0;i<numStrings; i++)
{
a[i] = calloc(maxStrLen + 1, 1);
}
return a;
}
关于c - 修改动态分配的 char* 二维数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43810308/