[英]How to pass a struct into a function
誰能告訴我解釋,如何將struct傳遞給函數? 我試圖將排序放入函數中,並將結構傳遞給它
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'類型時,類型不兼容” 我試圖像人們在互聯網上那樣傳遞結構
我試圖像人們在互聯網上那樣傳遞結構
不,你沒有。 您已經嘗試發明一種用於傳遞數組的新語法,但是不幸的是,這並不是用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);
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]的地址。
約翰
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.