簡體   English   中英

如何將指針數組的(結構)指針傳遞給函數?

[英]How to pass a (struct) pointer of an array of pointers to a function?

我在main之后聲明的函數中有一個指針結構和一個全局指針。 現在使用相同的指針名稱聲明函數就可以了。 但是,當我在另一個函數中調用它時(因為它像菜單類型的程序一樣),我不斷收到不同類型的錯誤。像需要表達式,意外類型等。我的問題很簡單,我該如何調用該函數的參數上班。 我已經好幾年沒有使用C了,所以該解決方案似乎比聽起來更簡單。 下面的代碼將向您展示我的意思。

StudentPtr studentArray StudentPtr ** studentArray結構StudentPtr * studentArray * StudentPtr studentArray [](將指針四處移動並使用struct作為前綴)

typedef struct Student {
    char *firstName;
    char *lastName;
    char *id;
    char *email;
} Student, *StudentPtr;

//Prototypes:
int fillData(StudentPtr studentArray,char* f, char* l, char* id, char* e,int n);
int displayData(StudentPtr studentArray, int n);
int displayDataAll(StudentPtr studentArray);

int main()
{
return 0;
}

int command(char line[])
{
//other code here
//some more code..
//......

//error below
if(lineSize==0)    /* If the command is empty, asks again for a command */
    {
        return 0;
    }

    else
    {
        if(strncmp(line,"1",lineSize)==0)
        {reset();}

        else if(strncmp(line,"2",lineSize)==0)
        {fillData(StudentPtr studentArray,char* f, char* l, char* id, char* e,int n);} //the first parameter here

        else if (strncmp(line,"3",lineSize)==0)
        {modify(StudentPtr studentArray,char* f, char* l, char* id, char* e,int n);} //here as well

        else if(strncmp(line,"4",lineSize)==0)
        {displayDataAll(StudentPtr studentArray);} //here too


        else if(strncmp(line,"5",lineSize)==0)
        {return 1;}
        else
        {noComm();}
    }

    return 0;
}

//example of the functions supposed to be used
int fillData(StudentPtr studentArray,char* f, char* l, char* id, char* e,int n)
{
    //get the start of the nth record
    //Ptr arithmetic
    StudentPtr currentStudentptr = studentArray+(n-1);

    //allocate memory for the character pointers
    currentStudentptr->firstName =malloc(sizeof(char)*20);
    strcpy(currentStudentptr->firstName,f);

    //... same for others

    return 0;

}

在這里調用函數應該正確地調用后面的函數。

您正在將用於函數聲明和定義的語法與用於調用函數的語法混合在一起:

    {fillData(StudentPtr studentArray,char* f, char* l, char* id, char* e,int n);} //the first parameter here

在函數調用中,您不必指定類型。 您只提供參數:

    {fillData(studentArray, f, l, id, e, n);}

您不顯示任何變量定義。 因此,我無法確定變量是否具有正確的類型,或者您是否需要在此處和此處添加一些&運算符...這就是為什么必須至少有一個完整的可驗證示例的原因。

暫無
暫無

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

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