使用双指针,如何用字符串填充2D?

问题描述

我正在逐行阅读文本文件。将每行放入二维数组。有时该程序可以工作,但是通常2d数组的第一个元素以乱码形式返回,例如:“ W @ ??”。

我看过StackOverflow上的其他示例,看不到这段代码出了什么问题。

int read_file(FILE* file,char ** strings) {
  char str[100];
  int n = 0;
  while(fgets(str,100,file)) {
      if(n > 0) {
        strings = realloc(strings,(n+1) * sizeof(char)); 
      }
      int len = strlen(str);

      if (len > 0 && str[len-1] == '\n') {
        str[len-1] = '\0';
      }
      len = strlen(str) +1;
      strings[n] = malloc(len * sizeof(char));
      strcpy(strings[n],str);
      puts(strings[n]);         //THIS PRINTS THE CORRECT OUTPUT
      n++;
  }

  puts(strings[0]);      //THIS PRINTS GIBBERISH,`W@??
  puts(strings[1]);
  puts(strings[2]);

return n;
}

    
int main(void) {
  FILE *file;
  file = fopen("data.txt","r");

  char ** strings = malloc(sizeof(char*));

  int n = read_file(file,strings);
  fclose(file);
  
  //print_strings(strings,n);


  puts(strings[0]);      //THIS PRINTS GIBBERISH,`W@??
  puts(strings[1]);
  puts(strings[2]);


  //freeAllocatedMemory(strings,n);
  return 1;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)