C在动态二维字符数组中插入字符串或(char *),分段错误
C insert a string or(char*) in a dynamic 2D char array, Segmentation fault
所以我需要编写一个二维 char
数组,它需要从一些子进程中填充。我不知道在 运行 时会返回多少行。
我编写了一个程序,该程序适用于插入的前三个字符串(或 char*
),但之后出现分段错误。该数组应保留其中的 values/strings 。这是代码:
全局行数:
static int rows = 1;
数组初始化:
char **output = (char **)malloc(sizeof(char*) * 1);
output[0] = (char *)malloc(sizeof(char) * 1023);
output[0][0] = '#';
添加:
char foo[1023];
insertArray(output, "bbb");
insertArray(output, foo);
insertArray(output, "bbb");
insertArray(output, "bbb");
实际上前 3 次工作正常
函数:
static void insertArray(char **c, char *itemToInsert) {
if (c[0][0] == '#') {
strncpy(c[0], itemToInsert, 1023);
}
else {
c = (char **)realloc(c, (rows + 1) * sizeof(char*));
for (int i = 0; i < rows+1; i++) {
c[i] = realloc(c[i],sizeof(char) * 1024);
}
strcpy(c[rows], itemToInsert);
rows++;
}
}
我就是想不通怎么了
您丢失了重新分配的结果,下次您尝试使用指向 output
的旧指针时。
您可以这样重新设计:
output = insertArray(output, ...);
output = insertArray(output, ...);
output = insertArray(output, ...);
...
static char **insertArray(char **c, char const *itemToInsert)
{
...
return c;
}
所以我需要编写一个二维 char
数组,它需要从一些子进程中填充。我不知道在 运行 时会返回多少行。
我编写了一个程序,该程序适用于插入的前三个字符串(或 char*
),但之后出现分段错误。该数组应保留其中的 values/strings 。这是代码:
全局行数:
static int rows = 1;
数组初始化:
char **output = (char **)malloc(sizeof(char*) * 1);
output[0] = (char *)malloc(sizeof(char) * 1023);
output[0][0] = '#';
添加:
char foo[1023];
insertArray(output, "bbb");
insertArray(output, foo);
insertArray(output, "bbb");
insertArray(output, "bbb");
实际上前 3 次工作正常
函数:
static void insertArray(char **c, char *itemToInsert) {
if (c[0][0] == '#') {
strncpy(c[0], itemToInsert, 1023);
}
else {
c = (char **)realloc(c, (rows + 1) * sizeof(char*));
for (int i = 0; i < rows+1; i++) {
c[i] = realloc(c[i],sizeof(char) * 1024);
}
strcpy(c[rows], itemToInsert);
rows++;
}
}
我就是想不通怎么了
您丢失了重新分配的结果,下次您尝试使用指向 output
的旧指针时。
您可以这样重新设计:
output = insertArray(output, ...);
output = insertArray(output, ...);
output = insertArray(output, ...);
...
static char **insertArray(char **c, char const *itemToInsert)
{
...
return c;
}