如何将指针传递给函数中的数组,修改它并正确返回?

时间:2012-11-24 11:26:27

标签: c pointers pass-by-reference

我试图在函数中传递指向数组的指针并将其返回。问题是在正确初始化之后,函数返回一个NULL指针。谁能告诉我,我的逻辑有什么问题?

这是我的函数,其中声明了数组:

void main()
{
     int errCode;
     float *pol1, *pol2;
     pol1 = pol2 = NULL;
     errCode = inputPol("A", pol1);
     if (errCode != 0)
     { 
         return;
     }

     // using pol1 array

     c = getchar();
}

这是初始化函数:

int inputPol(char* c, float *pol)
{
    pol= (float *) calloc(13, sizeof( float ) );
    while( TRUE )
    {
         // While smth happens
         pol[i] = 42;
         i++;
    };
}

1 个答案:

答案 0 :(得分:5)

您需要传递pol1的地址,因此main知道分配的内存在哪里:

void main()
{
    int errCode;
    float *pol1, *pol2;
    pol1 = pol2 = NULL;
    errCode = inputPol("A", &pol1);
    if (errCode != 0)
    { 
         return;
    }

    // using pol1 array

    c = getchar();
}

int inputPol(char* c, float **pol)
{
    *pol= (float *) calloc(13, sizeof( float ) );
    while( TRUE )
    {
         // While smth happens
         (*pol)[i] = 42;
         i++;
    };
}