0
所以我需要编写一个需要从某些子进程中填充的2维char
数组。我不知道在运行时会返回多少行。C在动态2D字符数组中插入字符串或(char *),分段错误
我做了一个程序,对前三个字符串(或char*
)插入效果很好,但在此之后,我得到分段错误错误。该数组应该保留它所包含的值/字符串。下面的代码:
全球行数:
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++;
}
}
我只是无法弄清楚什么是错
因此,这意味着我应该像一个临时的指针,一个重新分配回来?我到底怎么做? – Cnoffel
好了,现在没有什么工作了,对不起,我的错得到了一个错字,谢谢你的回答,它的作用像一个魅力 – Cnoffel