简体   繁体   English

将结构传递给函数并在其中循环

[英]passing a struct to a function and loop through it

Trying to pass a struct to a function and browse through it. 尝试将结构传递给函数并浏览它。 Is this the correct way to pass a struct to a function? 这是将结构传递给函数的正确方法吗? The for loop in the function view() doesn't seem to work. 函数view()中的for循环似乎不起作用。 Any help with that too would be appreciated. 任何帮助,也将不胜感激。

My structs: 我的结构:

typedef struct {
    char name[20];
    employee *list_employees;
    int empl_count;
} agency;
typedef struct {
    char name[30];
    int age;

} employee;

Important pars of the code: 代码的重要参数:

int main()
{
//...
int nmbr_agencies;
agency *list_agencies = malloc(sizeof(agency) * nmbr_agencies);
view(&list_agencies, &nmbr_agencies);
}
void view(agence *ListA[], int *nmbr)
{
    int i=0;
    for (i = 0; i < *nmbr; i++){
        printf("name of agency: %s\n", ListeA[i]->name);
        printf("number of employees\n, ListeA[i]->empl_count);
    }
}

No. 没有。

You should just pass a single array if that is what you have, not pretend (in the call) that you have an array of pointers which you don't have. 如果那是您所拥有的,您应该只传递一个数组,而不假装(在调用中)您拥有一个没有的指针数组。

Make the function: 使功能:

void view(const agency *list, size_t number);

and call it like so: 并这样称呼它:

view(list_agencies, nmbr_agencies);

Then inside the function, do direct accesses: 然后在函数内部,直接访问:

printf("name of agency: %s\n", list[i].name);

since you don't have an array of pointers. 因为您没有指针数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM