我想从标准输入中获取文本并将其存储到一个字符串数组中。但我希望字符串数组在内存中是动态的。我现在的代码如下:
char** readStandard()
{
int size = 0;
char** textMatrix = (char**)malloc(size);
int index = 0;
char* currentString = (char*)malloc(10); //10 is the maximum char per string
while(fgets(currentString, 10, stdin) > 0)
{
size += 10;
textMatrix = (char**)realloc(textMatrix, size);
textMatrix[index] = currentString;
index++;
}
return textMatrix;
}
我在打印时得到的结果是在数组的所有位置读取的最后一个字符串。
例子 阅读: 你好 好的 到 见面 你
打印: 你 你 你 你 你
为什么?我在网上搜索过。但是我没有发现这种错误。
最佳答案
您一遍又一遍地存储相同的地址 (currentString
)。尝试类似的东西
while(fgets(currentString, 10, stdin) > 0)
{
textMatrix[index] = strdup(currentString); /* Make copy, assign that. */
}
函数 strdup
不是标准的(只是广泛使用)。用malloc
+ memcpy
自己实现应该很容易。
关于c - 将文本存储在 C 中的字符矩阵中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7121596/