简体   繁体   English

如何将结构传递给函数

[英]How to pass a struct into a function

Could anyone tell me explain, how to pass struct into a function? 谁能告诉我解释,如何将struct传递给函数? I've tried to put my sorting into a function, and pass my struct into it 我试图将排序放入函数中,并将结构传递给它

typedef struct
{
    int weight;
    int price;
    Color color;
    Equip equip;
}Cars;

Cars automobil[5]; 

sort_cars(&automobil[NUMBER_OF_CARS]);

void sort_cars(struct Cars*automobil[NUMBER_OF_CARS]){
    int i,j;
    CarsmobilOne={};
    for(j=0; j<NUMBER_OF_CARS-1; j++)
    {
        for (i=0; i<NUMBER_OF_CARS-1; i++){
            if (automobil[i]->weight < automobil[i+1]->weight)
            {
                continue;

            }else{
                mobilOne = automobil[i];
                automobil[i] = automobil[i+1];
                automobil[i+1] = mobilOne;
            }
        }
    }

I got this error "incompatible types when assigning to type 'Cars' from type 'struct Cars*'|" 我收到此错误“从'struct Cars *'|类型分配给'Cars'类型时,类型不兼容” I've tried to do passing the struct as people do in the Internet 我试图像人们在互联网上那样传递结构

I've tried to do passing the struct as people do in the Internet 我试图像人们在互联网上那样传递结构

No, you have not. 不,你没有。 You have tried to invent a new syntax for passing an array, but unfortunately it is not the way arrays are passed in C language. 您已经尝试发明一种用于传递数组的新语法,但是不幸的是,这并不是用C语言传递数组的方式。

In C language, arrays do decay to pointers when they are passed as parameters to functions, so people usually pass the actual length along with the array. 在C语言中,将数组作为参数传递给函数时,数组的确会衰减到指针,因此人们通常将实际长度与数组一起传递。

So you should use: 因此,您应该使用:

void sort_cars(Cars*automobil, int number_of_cars){
    int i,j;
    Cars mobilOne={};
    for(j=0; j<number_of_cars-1; j++)
    {
        for (i=0; i<number_of_cars-1; i++){
            if (automobil[i]->weight < automobil[i+1]->weight)
            {
                continue;

            }else{
                mobilOne = automobil[i];
                automobil[i] = automobil[i+1];
                automobil[i+1] = mobilOne;
            }
        }
    }
}

And call it: 并称之为:

sort_cars(automobil, 5);
int carsSort(const void *a, const void *b) {
    return ((Cars *) a)->weight - ((Cars *) b)->weight;
}

void sortThem(Cars autom[]) {
    qsort(autom, NC, sizeof *autom, carsSort);
}

int main() {
    Cars automobil[NC];

    // Initialiase automobil here
    sortThem(automobil);

    for (int i = 0; i < NC; ++i)
    printf("%d\n", automobil[i].weight);
}

Remember one of the many wise sayings of K&R: "When an array name is passed to a function, what is passed is the location of the beginning of the array". 请记住K&R的许多明智说法之一:“将数组名称传递给函数时,传递的是数组开头的位置。”

Inside sortThem() "autom" is a variable whose value is the address of automobil[0]. 在sortThem()内部,“ autom”是一个变量,其值为automobil [0]的地址。

John 约翰

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

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