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

查看:26
本文介绍了在 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;
}

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

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)?

推荐答案

你需要调整*a 指针,这意味着你需要传递一个指针给*a.你这样做:

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天全站免登陆