gpt4 book ai didi

C将字符串保存到二维数组

转载 作者:太空宇宙 更新时间:2023-11-04 04:57:21 24 4
gpt4 key购买 nike

想法是从标准输入读取字符串,直到到达 EOF(格式为 "string - string")。然后,将字符串分成两个字符串并将它们保存到二维数组中。该数组是动态分配的,最初有 2 行和 20 列,但每次我想向它添加下一个字符串时我都想添加 2 行(函数 expandmat())。这是我的代码:

char ** alloc(int rows, int collums) {
char ** mat;
int i;
mat = malloc(sizeof (char *) * rows);
for (i = 0; i < rows; i++) {
mat[i] = malloc(sizeof (char) * collums);
}
return mat;
}

char ** addtoarray(char ** mat, char * string1, char * string2, int position) {

sscanf(string1, "%s", mat[positon]);
sscanf(string2, "%s", mat[positon+1]);
return mat;
}

char ** getinput(char * longstring, char * string1, char * string2) {

int position = 0, n = 2, max = 30;
char ** mat;
mat = alloc(n, max);
while (fgets(longstring, max, stdin)) {
sscanf(longstring, "%s - %s", string1, string2);
addtoarray(mat, string1, string2, positon);
n += 2;
position += 2;
mat = expandmat(mat, n);
}

return mat;
}

此外,如果这段代码中有什么地方没有任何意义,您能告诉我如何解决吗?

我知道这似乎是一项微不足道的任务,但它一直让我发疯。

感谢您的帮助。

最佳答案

查看 realloc C 函数来调整 mat 的大小。

expandmat 应该 realloc mat 以便您可以再添加两行(它也应该返回矩阵,因为 realloc 会在必要时将内存复制到新位置)

关于C将字符串保存到二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4910163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com