【问题标题】:How to pass a (struct) pointer of an array of pointers to a function?如何将指针数组的(结构)指针传递给函数?
【发布时间】:2019-04-16 06:03:44
【问题描述】:

我有一个指针结构和一个全局指针,可以在 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;

}

这里函数的调用应该正确调用更往下的函数。

【问题讨论】:

    标签: c function pointers struct


    【解决方案1】:

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

        {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 是强制性的原因。

    【讨论】:

    • 还有其他参数工作正常.. 我知道我可以让它更短,我没有想到。我很抱歉。这只是我遇到问题的第一个参数。
    • 更重要的是你应该完成它。包含编译所需的所有部分。
    • 我怀疑当你修复第一个参数时你不会得到任何其他参数的错误。
    • 好吧.. 就像你提到的那样,我基本上是在宣布不应该的时候,谢谢!
    猜你喜欢
    • 2021-11-02
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 2020-05-15
    • 2017-10-02
    • 1970-01-01
    相关资源
    最近更新 更多