c - 在将指针传递给函数之前,我必须始终对其进行初始化吗?

标签 c function null initialization malloc

在将 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/

相关文章:

javascript - 是否可以在javascript中获取父函数名称?

javascript:设置数组索引值不起作用?

sql - 为什么在使用 json 数据执行 sql 插入查询后,postgres 表在每一列中都显示 Null?

c - 如何将 Unicode 代码点打印为 C 中的字符?

c++ - 在桌面图标后面放一个窗口

c - 如何计算子弹击中的位置

c++ - 用于检测音频过零的选项

php - 在 PHP 函数/方法中返回的最佳实践

c - 关于在 C 中使用 "functions"

java - Java 中空 ("nil") UUID 的实例