在 C 中将文本存储在字符矩阵中
我想从标准输入中获取文本并将其存储到字符串数组中。但我希望字符串数组在内存中是动态的。我现在的代码如下:
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;
}
打印时得到的结果是在数组的所有位置中读取的最后一个字符串。
例子 阅读: 你好 好的 到 见面 您
打印: 你 你 你 你 你
为什么?我在互联网上搜索过。但我没有发现这种错误。
I want to take a text from the standard input and store it into an array of strings. But I want the array of strings to be dynamic in memory. My code right now is the following:
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;
}
The result I have while printing is the last string read in all positions of the array.
Example
Reading:
hello
nice
to
meet
you
Printing:
you
you
you
you
you
Why? I've searched over the Internet. But I didn't find this kind of error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您一遍又一遍地存储相同的地址 (
currentString
)。尝试类似的函数
strdup
不是标准的(只是广泛可用)。使用malloc
+memcpy
自己实现应该很容易。You are storing the same address (
currentString
) over and over. Try something likeThe function
strdup
is not standard (just widely available). It should be easy to implement it yourself withmalloc
+memcpy
.currentString
始终指向同一个内存区域,并且textMatrix
中的所有指针都将指向它currentString
always point to the same memory area and all the pointers intextMatrix
will point to it