传递指向函数的指针之前,我总是需要先初始化它吗?

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个回答

4

您应该更多地了解函数参数的工作原理。通常,在C语言中,参数是按值传递的(数组和函数有所不同,但首先要了解一下)。因此,在[1]中,您尝试释放未初始化的指针,因为函数中的赋值对主函数中的变量example没有任何影响。[2]是正确的。在[3]中,您根本没有分配内存,因此任何访问example指向的内容都将是无效的。[5]和[6]也不好,因为您将未初始化的值传递给realloc。


1
如果我将int *example;更改为int *example = NULL;,那么就可以了吗?(你所说的“[3]”是指[3]还是[4]?我问这个是因为我之前写错了[3]和[3],现在已经改正了) - ᴜsᴇʀ
1
[1] - 现在比以前好了,因为不会崩溃了,但仍然不太好,因为在函数中分配的内存从未被释放。主函数中的示例变量为NULL,并且free(example)没有任何作用。 - Wojtek Surowka
1
[3]和[4]都存在问题,因为没有分配任何内存,所以对example指向的任何内容的访问都是无效的。 - Wojtek Surowka
如果我将[1]更改为this,这样正确吗? - ᴜsᴇʀ
1
在我之前发布的链接中,我犯了一些错误(我传递给函数example而不是*example,并且在function()中,我将example写成了*example)。现在我已经更正了它们:这个链接正确吗? - ᴜsᴇʀ
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接