gpt4 book ai didi

c - 在 C 中的单独函数中初始化指针

转载 作者:行者123 更新时间:2023-11-30 16:16:17 24 4
gpt4 key购买 nike

我需要做一件简单的事情,我曾经在Java中做过很多次,但我陷入了C(纯C,而不是C++)。情况如下:

int *a;

void initArray( int *arr )
{
arr = malloc( sizeof( int ) * SIZE );
}

int main()
{
initArray( a );
// a is NULL here! what to do?!
return 0;
}

我有一些“初始化”函数,它应该将给定的指针分配给一些已分配的数据(无关紧要)。我应该如何给出一个指向函数的指针,以便修改该指针,然后可以在代码中进一步使用(在函数调用返回之后)?

最佳答案

您需要调整*a指针,这意味着您需要将指针传递给*a。你这样做:

int *a;

void initArray( int **arr )
{
*arr = malloc( sizeof( int ) * SIZE );
}

int main()
{
initArray( &a );
return 0;
}

关于c - 在 C 中的单独函数中初始化指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56667908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com