用C语言在字符矩阵中存储文本

用C语言在字符矩阵中存储文本,c,string,memory,dynamic,matrix,C,String,Memory,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(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;
}
打印时得到的结果是在数组的所有位置读取的最后一个字符串

范例 阅读: 你好 美好的 到 满足 你

印刷: 你 你 你 你 你

为什么??我在网上搜索过。但是我没有发现这种错误。

currentString总是指向同一个内存区域,textMatrix中的所有指针都会指向它

char** readStandard()
{
  int size = 0;
  char** textMatrix = (char**)malloc(size);
  int index = 0;
  char currentString[10];
  while(fgets(currentString, 10, stdin) > 0)
    {
      size += sizeof(char*);
      textMatrix = (char**)realloc(textMatrix, size);
      textMatrix[index] = strdup(currentString);
      index++;
    }
  return textMatrix;
}
currentString始终指向同一内存区域,textMatrix中的所有指针都将指向它

char** readStandard()
{
  int size = 0;
  char** textMatrix = (char**)malloc(size);
  int index = 0;
  char currentString[10];
  while(fgets(currentString, 10, stdin) > 0)
    {
      size += sizeof(char*);
      textMatrix = (char**)realloc(textMatrix, size);
      textMatrix[index] = strdup(currentString);
      index++;
    }
  return textMatrix;
}

您正在反复存储相同的地址currentString。试试像这样的东西

while(fgets(currentString, 10, stdin) > 0)
{
     textMatrix[index] = strdup(currentString); /* Make copy, assign that. */
}

strdup函数不是标准函数,只是可以广泛使用。用malloc+memcpy自己实现应该很容易。

您反复存储相同的地址currentString。试试像这样的东西

while(fgets(currentString, 10, stdin) > 0)
{
     textMatrix[index] = strdup(currentString); /* Make copy, assign that. */
}

strdup函数不是标准函数,只是可以广泛使用。用malloc+memcpy自己实现应该很容易。

为什么不起作用?char**readStandard{int size=0;char**textMatrix=char**mallocsize;int index=0;whileftestextmatrix[index],10,stdin>0{size+=10;textMatrix=char**realloctextMatrix,size;index++;}返回textMatrix;}@由于未为textMatrix[index]分配内存,EinsteinNatrium无法运行。问题已解决。我决定在每次迭代中使用textMatrix[index]=malloc10。然后是strcpytextMatrix[index],currentString。也许它不优雅。但我更喜欢避免使用strdup。谢谢你的回答。为什么不起作用呢?char**readStandard{int size=0;char**textMatrix=char**mallocsize;int index=0;whilefstextmatrix[index],10,stdin>0{size+=10;textMatrix=char**realloctextMatrix,size;index++;}返回textMatrix;}@由于未为textMatrix[index]分配内存,EinsteinNatrium无法运行。问题已解决。我决定在每次迭代中使用textMatrix[index]=malloc10。然后是strcpytextMatrix[index],currentString。也许它不优雅。但我更喜欢避免使用strdup。谢谢你的回答。