c - 从 C 指针数组获取我的值

标签 c arrays

在这里真的很挣扎,无法弄清楚如何从数组中获取我的值。

我首先声明这个数组,我想保存一组数字。我不知道为什么尺寸是 64,我只是很沮丧并给了它一个尺寸。

   char *numberList1[64];

然后我使用我找到的一些代码读取文件。

  FILE * fp;
   char * line = NULL;
   size_t len = 0;
   ssize_t read;
   char string[100];
   int counter = 0;

   printf("\n\nEnter name of File 1: ");
   scanf("%s", string);

   fp = fopen(string, "r");
   if (fp == NULL) {
       printf("invalid filename of %s",string);
       exit(EXIT_FAILURE);
    }
   while ((read = getline(&line, &len, fp)) != -1) {
       numberList1[counter] = line;
       counter++;
   }

现在,如果在 while 内说类似 printf("%s",numberList1[counter]); 的话,我会得到所有的数字。

但是,当我说出以下内容时,无论何时有数字,我都只打印出最后一项。 ( vector 长度)。

   int j;
   //vectorLength is the user-entered # of lines/numbers in the file.
   for (j = 0; j < vectorLength; j++) {
       printf("Writing out: %s \n", numberList1[j] );
       //write(pipe1[WRITE], currentNum, bitSize+1);  
   }

即如果我有数字,1、2、3、4 我会得到:4 4 4 4

我做错了什么???我试图找到有关理解 C 中指针和数组的指南,但我无法弄清楚......

最佳答案

您没有准备发送到 getline() 的参数适本地。根据文档:

If *lineptr is set to NULL and *n is set 0 before the call, then getline() will allocate a buffer for storing the line. This buffer should be freed by the user program even if getline() failed.

您想要为每一行创建一个新的行缓冲区,并且您至少似乎希望 getline() 为您创建该缓冲区,因此,在每次成功读取之后,并且一旦您保存了返回数组中由 getline() 分配的缓冲区指针,将行指针清回 NULL,并将长度参数清回零:

char * line = NULL;
size_t len = 0;
while ((read = getline(&line, &len, fp)) != -1 && counter < 64) 
{
   numberList1[counter++] = line;
   line = NULL; // <<==== ADDED
   len = 0;     // <<==== ADDED
}

free(line); // note: this is here because, though getline() failed, the
            // documentation for the api mandates its presence.

关于c - 从 C 指针数组获取我的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26153500/

相关文章:

php - 将数组存储在 Mysql 数据库的单个字段中的替代方案

具有无限循环和找零计数器 c 的收银机

c - 从 ‘int*’ 到 ‘unsigned int*’ 的无效转换 [-fpermissive]

将整数转换为 unsigned char* (int 221 到 "\xdd")

c - 在 C 中同时使用 gets() 和 printf() 会产生意想不到的结果

c++ - 将私有(private)指针数组初始化为 null

在 C 中正确等待线程终止

javascript - 从 JavaScript 中的数组中删除特定字符串

python - 数组中的 Numpy 条件乘法数据(如果为真乘以 A,则为假乘以 B)

jquery - 使用 jQuery 迭代 .getJSON 响应