首页 > 解决方案 > 学习处理文件,尝试通过引用 fcn 来传递结构数组

问题描述

我试图将一个结构数组传递给一个函数,然后让该函数处理一个文件并用值填充结构数组。该文件是一个文本文件,其中包含:

Gates M 60
Jobs M 55
Jane F 45

这将填充数组的结构。前任。person[0] 应该包含 Gates M 60。目前我没有得到这个程序的任何错误,但它根本没有将文件处理到 fscanf 的结构中。我引用的结构错了吗?

我还想知道是否有一种方法可以使 for 循环适用于任何大小的结构数组——这意味着我可以用什么替换 for 循环中的“2”条件,以便它不断填充数组足够的大小,直到它用完信息来处理?

#include <stdio.h>

struct Person
{
    char lastname[30];
    char gender;
    unsigned int age;
};

int function(struct Person array[])
{
    FILE *cfPtr;
    if((cfPtr = fopen("C:\\Users\\Nick\\Desktop\\textfile","r"))==NULL)
    {
        printf("File cannot be opened");
    }
    else
    {
        for(int i=0;i<2;i++)
        {
            fscanf(cfPtr,"%10s %c %3d",&array[i].lastname,&array[i].gender,&array[i].age);
        }
    }
}
int main(void)
{
    struct Person person[3];
    function(&person[3]);
    printf("%s %c %d\n",person[0].lastname, person[0].gender, person[0].age);
    printf("%s %c %d\n",person[1].lastname, person[1].gender, person[1].age);
    printf("%s %c %d\n",person[2].lastname, person[2].gender, person[2].age);
}

标签: carraysstructure

解决方案


目前我没有得到这个程序的任何错误,但它根本没有将文件处理到 fscanf 的结构中。我引用的结构错了吗?

你快到了,你错过了几件事:

  • for(int i=0;i<2;i++)应该是for(int i=0;i<3;i++)因为您永远不会像现在这样阅读第三行。
  • &使用 scanf 读取并存储在字符串中时删除。即更改fscanf(cfPtr,"...",&array[i].lastname,...);fscanf(cfPtr,"...",array[i].lastname,...);. 字符串 (ie char lastname[30];) 已经是一个数组,当按名称使用数组时,您实际上会在其第一个元素上获得一个指针,因此不需要那个&.
  • 函数 ( function(&person[3]);) 的调用不正确:&person[3]意味着您正在获取 person 数组的第 4 个(越界)元素的地址。您需要传递的是数组本身,它很简单function(person)。这与上一个项目符号中的原因相同。
  • int另外,当你什么都不返回时,为什么你的函数会返回一个?

我还想知道是否有一种方法可以使 for 循环适用于任何大小的结构数组——这意味着我可以用什么替换 for 循环中的“2”条件,以便它不断填充数组足够的大小,直到它用完信息来处理?

There is a way, namely using a dynamic array of type struct Person and allocating space to it at first with malloc and then by calling realloc in every iteration inside the function. Of course, you need to keep a counter of how many objects/lines you have read. You can find more about what you are asking by following this or this SO question, or searching and reading about dynamic arrays in C.


推荐阅读