在函数中的结构数组上使用 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);
    ....

我想做的是:

-将数组 (*student) 传递给函数

-使函数分配。数组

这是我写的函数

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 中对它的任何赋值对调用者来说都是不可见的。

您有两种选择来解决此问题:

  • Return 新分配的指针并在调用者中赋值,或者
  • 接受指向指针的指针,并使用间接运算符进行赋值。

这是第一个解决方案:

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);

你是对的,students 是作为值传递给 CreateStudentsArray() 的,你可以将其更改为接受 **stud,或者使它 return 指向已创建数组的指针。

我的建议是使用指向指针的指针,并使用 * 运算符来取消引用它。

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....