【问题标题】:How to pass a pointer to array in a function, modify it, and return back properly?如何在函数中传递指向数组的指针、修改它并正确返回?
【发布时间】:2012-11-12 12:09:27
【问题描述】:

我试图在函数中传递指向数组的指针并将其返回。问题是在正确初始化函数后返回一个 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++;
    };
}

【问题讨论】:

  • 您需要提高编译器警告级别(或注意您的警告),这样您就不会在没有return 语句的情况下编写非空函数。 :-/
  • 您发布的代码是您正在运行的完整代码吗?我在 inputPol 函数中看到了无限循环,并且您没有返回错误代码。
  • 附注您不需要在 C 中转换 calloc 的结果

标签: c pointers pass-by-reference


【解决方案1】:

你需要传递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++;
    };
}

【讨论】:

    猜你喜欢
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 2016-11-07
    • 2018-09-23
    • 1970-01-01
    • 2019-11-07
    相关资源
    最近更新 更多