我們假設我將一個指向數組或結構的指針傳遞給函數。我應該在函數內部分配內存還是函數被稱爲
像
myfun1(struct node *head, int* arr, int N){
head = malloc(sizeof head);
arr = malloc(N* sizeof arr);
......
}
myfun2(struct node *head, int* arr){
...
}
,我來自另一個功能
void CallingFunction(void){
struct node* head1 = NULL;
int *arr1;
struct node* head2 = NULL;
int *arr2;
int N = 10;
head2 = malloc(sizeof head);
arr2 = malloc(N* sizeof arr);
myfunc1(head1, arr1, N);
myfunc2(head2, arr2);
}
其中調用函數的方法是更好的調用這些功能。 myfun1
或myfun2
?
我應該從CallingFunction還是內部函數分配內存給結構和數組?
編輯:
正如指出的那樣,程序有一些錯誤,讓我們說我糾正這兩個錯誤。
head = malloc(sizeof *head);
myfunc2(head2, arr2, N);
現在,會是什麼答案。我應該在callingFunction()還是myfun()中分配內存。
mybad,可以說我糾正了錯誤head = malloc(sizeof * head);我在myfunc2中傳遞N那麼哪一個會更好? –
我不明白,如果你將'N'傳遞給'myfun2'這兩個函數都是平等的,不是嗎? –
for myfun1()我在myfun1()和myfun2()中分配內存,我在callingFunction()中分配內存。 –