【问题标题】:How do I fill a string array from a textfile using double pointers?如何使用双指针从文本文件中填充字符串数组?
【发布时间】:2019-11-15 18:25:21
【问题描述】:

我正在尝试读取文件并使用指针将字符串保存在数组中,但我遇到了问题。有人可以给我建议吗?

// not allowed to change these two rows
char **Lines;
Lines = (char**)malloc(sizeof(char*)*maxLines);

...

FILE *fp;
fp = fopen(fileName, "r");     // fileName already exists here
int i=0, j=0;

while(i<maxLines){
    Lines[i] = (char*)malloc(maxLength * sizeof(char)); 
    i++;
}

// No string will be longer than "maxLenght" so no buffer is used.
while(fgets(Lines[j] , maxLength, (FILE*) fp) != NULL && j < maxLines) 
{
        j++
}

我想用文件中的每个字符串填充“行”。我不断收到分段错误。 谢谢!

【问题讨论】:

  • 您分配了一个指针数组(每行一个),但没有为任何它们分配内存。您可以先将每一行读入一个大缓冲区,以便知道它有多长,然后分配足够的内存并复制它。
  • 这个问题,或者它的一个变体,每天被问多次。提问前请先搜索!
  • 不知道是不是segfault的原因,但在第二个循环中i &lt; maxLines应该是j &lt; maxLines

标签: c pointers readfile double-pointer


【解决方案1】:

在第二个 while 循环中替换“||”用“&&”。

即使在达到 maxlines 之后,这种情况下的循环也会继续执行。

【讨论】:

  • 我犯了一个愚蠢的错误。谢谢。我仍然遇到段错误:(
  • 现在您正在使用 j 作为 fget,使用 j
  • 这个愚蠢的问题和 WeatherVane 解决的另一个问题修复了它。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-09
相关资源
最近更新 更多