Ein*_*ium 1 c memory string dynamic matrix
我想从标准输入中获取文本并将其存储到字符串数组中.但我希望字符串数组在内存中是动态的.我现在的代码如下:
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;
}
Run Code Online (Sandbox Code Playgroud)
打印时的结果是在数组的所有位置读取的最后一个字符串.
阅读示例:您好,很高兴见到您
印刷:你是你,你
为什么?我在互联网上搜索过.但我没有发现这种错误.
您currentString一遍又一遍地存储相同的地址().尝试类似的东西
while(fgets(currentString, 10, stdin) > 0)
{
textMatrix[index] = strdup(currentString); /* Make copy, assign that. */
}
Run Code Online (Sandbox Code Playgroud)
该功能strdup不是标准功能(只是广泛使用).使用malloc+ 可以很容易地实现它memcpy.