使用free(array [i]);會導致問題/奇怪的錯誤,因爲您試圖釋放一個指針,其值(指針)在前一行中已更改。
代碼 array [i] ='\ 0';
可能沒有所需的結果,因爲它將指針值設置爲不是字符內容。也許sprintf(array [i],「\ 0」);會更好
char **array=NULL; //(Helps you to give it an initial value pointing to NULL)
array = malloc(arr_size+1);
if (!array[i])
{
// array == NULL which is not right after malloc
// there has been an error with malloc, trap and exit somehow
}
else
{
// Use array as you wish as it has been allocated, take care not to
// run past the end of the array length
}
if (array[i]) free(array[i]); // checks that it is not NULL anymore, as NULL does not need freeing.
你可以擴大IF語句:(指上面一樣,但包括強制釋放變量NULL)
if (array[i]!=NULL)
{
free(array[i]);
array[i] = NULL;
}
這是否編譯?數組的聲明是什麼? –
char **數組; array = malloc(20 * sizeof(char *)); – Pavoo
那麼爲什麼單引號呢? –