c - 当使用数组标识单个结构时,使用函数更改 typedef 字段

标签 c arrays function struct typedef

这似乎是一个非常具体的问题,我很难找到任何类型的答案。

我正在尝试使用 typedef 结构来存储用户信息。我使用 cust[x].firstName 等格式来区分一个客户和另一个客户。因为我在头文件中定义了这个结构,所以我的理解是通过改变函数内部结构的字段,这些变化应该反射(reflect)在 main 中。然而,情况似乎并非如此。

    typedef struct
 {
    char firstName[99];
    char lastName[99];
    int numOrders;
    char orders[99][99];
    float orderPrice[99][99];
    float orderNum[99][99];
 }Info;

int infoGet(FILE*,int);
int main()
{
int orderNum,i;
 FILE*input = fopen("input.txt","r");
 FILE*output = fopen("invoices.txt","w+");

fscanf(input,"%d",&orderNum);
Info cust[10];

infoGet(input,orderNum)
printf("%s %.2f %.2f\n",cust[0].orders,cust[0].orderPrice[1][0],cust[0].orderNum[1][0]);
}



int infoGet(FILE*input,int orderNum)
{
    int i,j;
    char space;
    Info cust[10];
    for(i = 0;i < orderNum;i++)
    {
        fscanf(input,"%s %s",cust[i].firstName,&cust[i].lastName);
        printf("%s %s\n",cust[i].firstName,cust[i].lastName);
        fscanf(input,"%d",&cust[i].numOrders);
        printf("This person has %d items to order\n",cust[i].numOrders);
        for(j=0;j < cust[i].numOrders;j++)
        {
            fscanf(input,"%s %f %f",cust[i].orders,&cust[i].orderPrice[1][j],&cust[i].orderNum[1][j]);
            printf("%s %.2f %.2f\n",cust[i].orders,cust[i].orderPrice[1][j],cust[i].orderNum[1][j]);
        }
    }
 }

main 中的最后一个 printf 语句应该打印函数中最后一个 fscanf 扫描的内容,但事实并非如此。我需要将结构传递给函数吗?或者我还需要做些什么来保持这个结构不变?

最佳答案

Since I'm defining this struct in the header, it's my understanding that by altering the fields of the struct inside a function, these changes should be reflected in main.

这是误会。 header 中的定义定义了一个类型。这不是可以修改的对象,而是创建和使用该类型实例的所有代码所需的定义。这就是 main()infoGet() 中发生的情况,您可以在其中使用以下语句实例化 Info 对象的数组:

Info cust[10]; // instantiates an array of 10 Info objects

现在,关于实际问题:您的函数 infoGet 有自己的 local 数组 Info cust[10]。在函数中修改它在函数外没有影响。您需要将数组从 main 传递到函数中。例如,

int infoGet(FILE*input, Info* cust, int orderNum)
{
    int i,j;
    char space;
    for(i = 0;i < orderNum;i++)
    {
    ....
}

int main()
{
  int orderNum,i;
  FILE*input = fopen("input.txt","r");
  FILE*output = fopen("invoices.txt","w+");

  fscanf(input,"%d",&orderNum);
  Info cust[10]; // Careful! What if orderNum is > 10?

  infoGet(input, cust, orderNum)

请注意,您应该检查orderNum 是否不超过10,或者分配一个可变长度的数组:

  Info cust[orderNum];

关于c - 当使用数组标识单个结构时,使用函数更改 typedef 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29839693/

相关文章:

用于生成/提取文件类型元数据(音频或图像或等)的 C 库

计算包含 1 的子集的数量

arrays - 从数组中查找对象匹配

ios - swift 无法将数据存储回数组,即使在 seguing 期间也是如此

根据值干净地访问结构数组

c++ - 模板函数中的通用模板参数

c - 诅咒中的多个游标

不重复的字符串组合 C

javascript - 如何将自定义值传递给现有函数(不更改函数)?

c - 在 C 语言中——如何定义以指针作为参数的函数?