在用C单独的函数初始化一个指针 [英] Initializing a pointer in a separate function in C
问题描述
我需要做一个简单的事情,这在我以前在Java中做很多次,但我用C很卡(纯C,不是C ++)。情况是这样的:
I need to do a simple thing, which I used to do many times in Java, but I'm stuck in C (pure C, not C++). The situation looks like this:
int *a;
void initArray( int *arr )
{
arr = malloc( sizeof( int ) * SIZE );
}
int main()
{
initArray( a );
// a is NULL here! what to do?!
return 0;
}
我有一些初始化功能,这应该给定的指针分配到一些分配数据(无所谓)。我应该怎样给一个指向函数的指针,以该指针将被修改,然后就可以进一步在code(即函数调用返回后)一起使用?
I have some "initializing" function, which SHOULD assign a given pointer to some allocated data (doesn't matter). How should I give a pointer to a function in order to this pointer will be modified, and then can be used further in the code (after that function call returns)?
推荐答案
您需要调整*的指针,这意味着你需要一个指针传递给*一个。你是这样做的:
You need to adjust the *a pointer, this means you need to pass a pointer to the *a. You do that like this:
int *a;
void initArray( int **arr )
{
*arr = malloc( sizeof( int ) * SIZE );
}
int main()
{
initArray( &a );
return 0;
}
这篇关于在用C单独的函数初始化一个指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!