c - 返回从文件中读取的数字数组

标签 c

我有一个作业,我需要在其中编写一个函数,该函数将数字从文件读取到数组并返回该数组(指向第一个元素的指针)。 我写了一个从文件读取到数组的函数,但我不知道如何返回它。

void to_array(FILE* file, int bufsize){
char arr[bufsize][100];
fseek(file, 0, SEEK_SET);
int i = 0;
while(!feof(file)){
    fscanf(file, "%s", arr[i]);
    i++;
}

如果有任何想法,我将不胜感激。

最佳答案

void to_array(FILE* file, int bufsize){
  char arr[bufsize][100];
  ...
}

你的数组是本地的,如果你返回它的地址它将无法使用它

一种方法是通过 malloc 在头部分配它,另一种方法是在参数中接收该数组以填充它。请注意,如果没有恒定大小,它就不能是静态的

不要使用feof检查fscanf的结果

你读的是数字,所以数组一定是数字数组,让我们考虑int

函数接收文件描述符和指向变量的指针的示例,该变量将包含放置到数组中的元素数,函数返回所需的堆中分配的数组

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

int * to_array(FILE * fp, size_t * sz)
{
  int * a = malloc(0); /* initially empty */
  int v;

  *sz = 0; /* initially no element */

  while (fscanf(fp, "%d", &v) == 1) {
    a = realloc(a, (++*sz)*sizeof(int)); /* add an entry */
    a[*sz - 1] = v; /* set entry */
  }

  return a;
}

int main()
{
  size_t sz;
  int * a = to_array(stdin, &sz);

  /* check */
  for (size_t i = 0; i != sz; ++i)
    printf("%d\n", a[i]);

  /* free used memory */
  free(a);

  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall a.c
pi@raspberrypi:/tmp $ echo 11 22 33 | ./a.out
11
22
33
pi@raspberrypi:/tmp $

valgrind 下执行:

pi@raspberrypi:/tmp $ echo 11 22 33 | valgrind ./a.out
==10080== Memcheck, a memory error detector
==10080== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==10080== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==10080== Command: ./a.out
==10080== 
11
22
33
==10080== 
==10080== HEAP SUMMARY:
==10080==     in use at exit: 0 bytes in 0 blocks
==10080==   total heap usage: 6 allocs, 6 frees, 5,144 bytes allocated
==10080== 
==10080== All heap blocks were freed -- no leaks are possible
==10080== 
==10080== For counts of detected and suppressed errors, rerun with: -v
==10080== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)

该函数每次都分配一个额外的条目,可以按 block 给定数量的条目来执行,而不必每次都必须添加一个条目。

关于c - 返回从文件中读取的数字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55928530/

相关文章:

c++ - Open Watcom 的优点和缺点

c - 如何有效地合并 Ruby C API 中的两个散列?

c++ - 这个数组如何合法?

c - 难以理解连续的递归调用

c - TicTacToe 打印获胜者

c - 移动数组中的元素

python - 已安装字体列表 OS X/C

c - 分配给类型时不兼容的类型 - C

C : cost of copying data from heap to stack?

c - 为什么即使我刚刚编译了源代码,我的 makefile 也会重新编译?