C: 如何将字符串存储到 “char *myArray[100]” 数组中?

标签 c string

我在 C 中创建了这段代码来逐行读取文本文件并将每一行存储到数组的一个位置:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static const int MAX_NUMBER_OF_LINES = 100000;
static const char filename[] = "file.csv";

int main ( void )
{

  // Read file and fill the Array
  char *myArray[MAX_NUMBER_OF_LINES];
  int numberLine = 0;
  FILE *file = fopen (filename, "r");
  if (file != NULL)
  {
      char line [128];
      while (fgets (line, sizeof line, file) != NULL)
      {
          myArray[numberLine] = line;
          numberLine++;    
      }
      fclose (file);
  }

  // Print the Array
  for (int i = 0; i<numberLine; i++)
  {
    printf("%d|%s", i, myArray[i]);
  }
}

但是打印数组时,它是空的。我做错了什么?

最佳答案

因为您需要将行复制到数组的缓冲区中。

您需要为数组的每个元素中的字符串分配空间,然后使用类似strncpy 的方法将每个 移动到每个myArray 插槽。

在您当前的代码中,您只是将相同的引用 - 复制到您的 line 缓冲区 - 到每个数组槽中,所以最后, myArray 的每个槽应该指向内存中的相同字符串。

根据 Shoaib 的建议,strdup 如果可用,将节省一个步骤,因此请尝试:

myArray[i] = strdup(line);

那里没有错误处理,请参阅 strncpy 的文档和 strdup .

或者,您可以向 myArray 添加一个维度:

char myArray[MAX_NUMBER_OF_LINES][100];

关于C: 如何将字符串存储到 “char *myArray[100]” 数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972060/

相关文章:

c++ - 重叠的字符串

c# - String.Join 与字符串连接 : Code Improvement

c - 如何通过串口与NCI NFC Controller 通信?

c - 关于c语言的一道题

c - 静态结构警告空声明中无用的存储类说明符

c++ - 手动将整数变量放入字符串中

c# - 格式化字符串字面量

c - 如何在 C 结构中定义变量的值?

c - 用 C 读取文本文件,在多个点处停止,将其分成多个部分

JavaScript 正则表达式