如何将指针数组的(结构)指针传递给函数?

时间:2019-04-16 06:03:44

标签: c function pointers struct

我有一个指针结构和一个全局指针,可以在main之后声明的函数中使用。现在使用相同的指针名称声明函数就可以了。但是,当我在另一个函数中调用它时(因为它像菜单类型的程序一样),我不断收到不同类型的错误。像需要表达式,意外类型等。我的问题很简单,我该如何调用该函数的参数去工作。我已经好几年没有使用C了,所以该解决方案似乎比听起来更简单。下面的代码将向您展示我的意思。

StudentPtr studentArray StudentPtr ** studentArray struct 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;

}

此处的函数调用应正确地调用下一级的函数。

1 个答案:

答案 0 :(得分:2)

您正在将函数声明和定义的语法与调用函数的语法混合:

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

在函数调用中,您不必指定类型。您只提供参数:

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

您没有显示任何变量定义。因此,我无法确定变量是否具有正确的类型,或者您是否需要在这里和那里添加一些&运算符... 这就是minimum complete verifyable example是强制性的原因。