繁体   English   中英

在函数中的结构数组上使用calloc

[英]using calloc on an array of struct, in a function

这是我的结构

//global
typedef struct {
    char idCode[MATLENGTH + 10];
    char *name;
} stud;

总的来说,我这样做

Int main() {

    stud *students;
    createStudentArray(students);
    ....

我正在尝试做的是:

-将数组(*学生)传递给函数

-使函数分配。 数组

这是我写的功能

createStudentArray(stud *students) {

    //I get this value from a file
    int nstud = 3;
    students calloc(nstud, sizeof(students));
    return;
}

问题是:

-当我尝试为学生字段分配任何值时,它不起作用

恩。

Int main() {

    stud *students;
    createStudentArray(students);
    ....
    strcpy(students[0].name, "Nicola"); //this is where i get the error

我的猜测是,以某种方式,我没有正确分配数组,因为当我尝试执行此操作时,

strcpy(students[0].name, "Nicola");

在createStudentArray函数中,它可以正常工作。 所以看起来我是通过值而不是通过引用传递数组。

在此先感谢您的帮助。

这是因为students指针是按值传递的。 createStudentArray内部对其的任何分配对于调用者而言都是不可见的。

您可以通过以下两种方法解决此问题:

  • 返回新分配的指针并在调用方中分配它,或者
  • 接受一个指向指针的指针,并分配一个间接运算符。

这是第一个解决方案:

stud *createStudentArray() {
    //I get this value from a file
    int nstud = 3;
    stud *students = calloc(nstud, sizeof(students));
    ...
    return students;
}
...
stud *students = createStudentArray();

这是第二个解决方案:

void createStudentArray(stud ** pstudents) {
    //I get this value from a file
    int nstud = 3;
    *pstudents = calloc(nstud, sizeof(students));
    ...
}
...
stud *students;
createStudentArray(&students); // Don't forget &

在C语言中,参数是通过值而不是引用传递的。

对被调用方函数中的参数所做的更改不会影响调用方函数中的变量。

要从被调用者函数修改调用者的变量,请使用指针。

createStudentArray(stud **students) {

    //I get this value from a file
    int nstud = 3;
    *students = calloc(nstud, sizeof(stud)); // this should be sizeof(stud), not students
    return;
}

int main() {

    stud *students;
    createStudentArray(&students);
    ....

这是因为在您的函数中,仅将本地指针分配给分配的内存块的新地址。 要从外部获取它,您需要使用类似这样的指针:

createStudentArray(stud **students) { ... }

并这样称呼它:

createStudentArray(&students);

您是正确的,将学生作为值传递给CreateStudentsArray(),或者将其更改为接受** stud,或者使它返回指向创建的数组的指针。

我的建议是使用一个指向指针的指针,并使用*运算符将其取消引用。

createStudentArray(stud **students) {

    //I get this value from a file
    int nstud = 3;
    *students = calloc(nstud, sizeof(students));
    return;
}

    void main(){
    stud = *students;
    ...
    createStudentsArray(&students);
    ...
    strcpy....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM