繁体   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