簡體   English   中英

無法將整個結構數組傳遞給函數

[英]Trouble passing a whole structure array to a function

一般而言,我對C ++和編程還是有點陌生​​。 我正在為舊的Gameboy版本制作寵物小精靈重制版,很有趣,但我很難通過整個結構作為爭論。

這是簡化版,以突出我遇到的問題:

struct Enemy_Pokeman
{
    string opp_name;
    int num_pokeman;
    int pokeman_LVL;                  
};   

void pl_Pokeman(Enemy_Pokeman); 

void pokeman_data(string opp_name, int num_pokeman, int pokeman_ID[], int pokeman_LVL[],
                  int purpose)
{
    Enemy_Pokeman enemypokeman[num_pokeman];

    enemypokeman[0].opp_name = opp_name;
    enemypokeman[0].num_pokeman = num_pokeman;
    for(int i=0; i<num_pokeman; i++)
        enemypokeman[i].pokeman_LVL = pokeman_LVL[i];

    pl_Pokeman(enemypokeman);                   //Function call - Codeblocks detects error
                                            //on this line
}

void pl_Pokeman(Enemy_Pokeman enemy)        
{
    cout << endl;
}

抱歉,如果這沒有意義,我不想發布整個內容,因此我將其切碎了。 問題在於它不會接受Enemy_Pokeman的爭論。

當您傳入an array of Enemy_Pokeman函數pl_Pokeman僅采用Enemy_Pokeman類型

您更新pl_Pokeman function以將數組作為輸入:

void pl_Pokeman(Enemy_Pokeman enemy[], int arraySize);

要么

template<typename T, size_t N>
void pl_Pokeman(Enemy_Pokeman (&enemy)[N]) 

對於單一結構-

當您將結構作為參數傳遞時,應與&運算符一起傳遞。

pl_Pokeman(&enemypokeman); // Fix 1

捕獲它時,您需要使用Structure指針捕獲它。

void pl_Pokeman(Enemy_Pokeman *); // Fix 2

對於結構數組-

pl_Pokeman(&enemypokeman,size); // pass it with size

在抓住它的同時

void pl_Pokeman(Enemy_Pokeman (*)[], int );

您將整個Enemy_Pokeman數組傳遞給函數,而不僅僅是一個元素。 函數只需要一個元素。 同樣,您正在函數中創建該數組,因此它是一個局部變量。 如果函數pokemon_data返回,則該數組將被銷毀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM