1

I am attempting to pass a pointer to array in a function and return it back. The problem is that after correct initializing the function returns a NULL-pointer. Can anyone tell me, what is the issue with my logic?

Here is my function, where array is declared:

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

     // using pol1 array

     c = getchar();
}

And here is the function with initialization:

int inputPol(char* c, float *pol)
{
    pol= (float *) calloc(13, sizeof( float ) );
    while( TRUE )
    {
         // While smth happens
         pol[i] = 42;
         i++;
    };
}
3
  • 4
    You need to turn up your compiler warning level (or pay attention to your warnings) so you don't write non-void functions without return statements. :-/ Commented Nov 24, 2012 at 11:31
  • 2
    Is the code that you are posting the complete code you are running? I see and infinite loop in the inputPol function and you are not returning the error code. Commented Nov 24, 2012 at 11:31
  • p.s. you don't need to cast result of calloc in C Commented Nov 24, 2012 at 19:22

1 Answer 1

5

You need to pass the address of pol1, so main knows where the allocated memory is:

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++;
    };
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.