【问题标题】:How to pass a struct into a function如何将结构传递给函数
【发布时间】:2017-10-09 15:36:34
【问题描述】:

谁能告诉我解释一下,如何将结构传递给函数?我试图将我的排序放入一个函数中,并将我的结构传递给它

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

我收到此错误“从类型'struct Cars *'分配给类型'Cars'时不兼容的类型|”我试图像人们在互联网上那样传递结构

【问题讨论】:

  • 唉,在哪一行?请发帖minimal reproducible example
  • 在这一行:mobilOne = automobil[i];
  • 您没有在代码中的任何位置定义struct Cars
  • struct Cars 更改为Cars。您从未将Cars 定义为结构标记,仅定义为typedef
  • 一个错误是关于你如何声明结构的。您使用 typedef 创建一个 struct Cars,但您给函数一个 struct Carsnot Cars 这是您创建的结构。

标签: c function struct parameter-passing


【解决方案1】:

我尝试像互联网上的人们那样传递结构

不,你没有。您试图发明一种新的传递数组的语法,但不幸的是它不是在 C 语言中传递数组的方式。

在 C 语言中,数组在作为参数传递给函数时会衰减为指针,因此人们通常将实际长度与数组一起传递。

所以你应该使用:

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

并称它为:

sort_cars(automobil, 5);

【讨论】:

    【解决方案2】:
    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);
    }
    

    记住 K&R 中的一句名言:“将数组名传递给函数时,传递的是数组开头的位置”。

    在sortThem()中,“autom”是一个变量,其值为automobil[0]的地址。

    约翰

    【讨论】:

    • 很高兴看到一些 C 函数式编程。代码重用很好。
    猜你喜欢
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多