在将 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
的初始化在main.
#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));
最佳答案
您应该了解有关函数参数如何工作的更多信息。通常在 C 中,参数是按值传递的(数组和函数的处理方式不同,但首先要处理)。所以在 [1] 中你尝试释放未初始化的指针,因为函数中的赋值不会对 main 中的变量 example 做任何事情。 [2] 很好。在 [3] 中你根本不分配内存,所以对 example 指向的任何访问都是无效的。 [5] 和 [6] 不好,因为您将未初始化的值传递给 realloc。
关于c - 在将指针传递给函数之前,我必须始终对其进行初始化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21172130/