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

Using a function to alter typedef fields when individual structs are identified using an array

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

我正在尝试使用 typedef 结构来存储用户信息。我使用 cust[x].firstName 等格式来区分一个客户和另一个客户。因为我在头文件中定义了这个结构,所以我的理解是通过改变函数内部结构的字段,这些变化应该反映在 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中的定义定义了一个类型。这不是可以修改的 object ,而是创建和使用该类型实例的所有代码都需要的定义。这就是 main()infoGet() 中发生的情况,您在其中使用以下语句实例化 Info object 的数组:

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];