开发者

Storing text in a char matrix in C

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++;
    }
  retu开发者_开发百科rn 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.


You are storing the same address (currentString) over and over. Try something like

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

The function strdup is not standard (just widely available). It should be easy to implement it yourself with malloc + memcpy.


currentString always point to the same memory area and all the pointers in textMatrix will point to it

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜