[英]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.