gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:43:52 24 4
gpt4 key购买 nike

我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com