3
在將一個在main()
中定義的指針傳遞給一個函數之前,我必須初始化它,還是可以將它初始化爲函數?還是一樣?我可以用NULL
初始化它嗎?在傳遞函數指針之前,我必須始終初始化它?
我寫了一些代碼爲例。沒關係?
[1]int *example
的初始化在函數中。
#include <stdio.h>
#define DIM (10)
void function (int *);
int main()
{
int *example;
function (example);
/* other code */
free(example);
return 0;
}
void function (int *example)
{
/* INITIALIZATION */
example = malloc (DIM * sizeof(int));
/* other code */
return;
}
[2]的int *example
初始化是在主。
#include <stdio.h>
#define DIM (10)
void function (int *);
int main()
{
int *example;
/* INITIALIZATION */
example = malloc (DIM * sizeof(int));
function (example);
/* other code */
free(example);
return 0;
}
void function (int *example)
{
/* other code */
return;
}
[3]初始化是在main()
與NULL
。
#include <stdio.h>
void function (int *);
int main()
{
/* INITIALIZATION */
int *example = NULL;
function (example);
/* other code */
free(example);
return 0;
}
void function (int *example)
{
/* other code */
return;
}
[4]初始化與NULL
的功能。
#include <stdio.h>
void function (int *);
int main()
{
int *example;
function (example);
/* other code */
free(example);
return 0;
}
void function (int *example)
{
example = NULL;
/* other code */
return;
}
[5]同爲[1]但example = realloc (example, DIM * sizeof(int));
[6]同爲[2]但example = realloc (example, DIM * sizeof(int));
如果在[1]中將'int * example;'改成'int * example = NULL;'那麼它是正確的? (與_「[3]」_你是指[3]還是[4]?我問你這是因爲我寫錯誤[3]和[3],現在我有正確的) –
[1] - 比以前,因爲不會崩潰,但仍然不好,因爲在函數中分配的內存永遠不會釋放。 main中的示例變量爲NULL,並且free(example)不執行任何操作。 –
在沒有分配內存的意義上,[3]和[4]都是有問題的,因此對示例指向的訪問將無效。 –