在用C单独的函数初始化一个指针 [英] Initializing a pointer in a separate function in C

查看:125
本文介绍了在用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆