我創造了這個數組:如何釋放此char **數組?
char** command=malloc(sizeof(*command)*MAX_COMMANDS+1);
,之後的每一個命令[I]得到這個:
command[i]=malloc(sizeof(*command[i])*strlen(token)+1);
如何釋放命令二維數組?
我創造了這個數組:如何釋放此char **數組?
char** command=malloc(sizeof(*command)*MAX_COMMANDS+1);
,之後的每一個命令[I]得到這個:
command[i]=malloc(sizeof(*command[i])*strlen(token)+1);
如何釋放命令二維數組?
有一個拇指規則 - 對malloc的每次調用都對應於一次釋放的調用,通常情況下,您將按照其分配的相反順序釋放內存。在這種情況下,您應該遍歷command
,每個command[i]
調用free
,然後纔可以free
command
。
int i =0;
while (i < MAX_COMMANDS)
{
free(command[i]);
++i;
}
這不會釋放'命令'本身 –
他詢問釋放「命令第二陣列」,所以我認爲他不想釋放命令本身,只是它的子陣列... – Matthieu
公平的(原來的問題wasn' t完全清晰),所以+1 –
你可以這樣做。
#include <stdio.h>
#include <stdlib.h>
int main(void){
char** command = malloc(sizeof(char*)*5);
for(int i=0;i<5;i++){
*(command+i) = malloc(sizeof(char)*6);
}
//memory allocated for 5 rows and 6 columns 2D array
for(int i=0;i<5;i++){
free(*(command+i));
}
free(command);
//memory is free for 5 rows and 6 columns 2D array
return 0;
}
如果你命令[i]而不是命令+ i,它會更容易被讀取。 –
在循環中釋放'command [i]',然後釋放'command'?這有什麼問題?這只是顛倒'malloc'的順序。 – luk32
遍歷'command',釋放條目,然後釋放'command'本身。不要留下無法訪問的非自由指針數組。 –
這是**不是** 2D陣列!一個二維數組可以通過一次調用「malloc」和「free」,並且是一種非常不同的類型。 – Olaf