Noe Cano
Noe Cano

Reputation: 515

Failed to get the contents of a pointer in C

I have the following statements in a program in C and they cannot be changed:

struct struct_handle;
struct struct_handle *com_Connect(const char *val1, void *priv, int timeout_msec, enum com_ErrorCodes *com_errno);

I create this function:

void foo(struct_handle *handle)
{
    enum com_ErrorCodes com_errno;

    do
    {
        handle = com_Connect("val1", NULL, 10000, &com_errno);

        if(handle == NULL) 
        {
            //ERROR handle is NULL
        }
    }
    while(handle == NULL);

    //HERE handle is not NULL
}

This is the main function:

int main(int argc, char const *argv[])
{
    struct struct_handle *handle;

    foo(handle);

    if(handle == NULL)
    {
        //ALWAYS handle IS NULL
    }

    return 0;
}

The function that i create foo() is to send a "handle" and receive it once it is different from NULL, I know it is different from NULL because the function returns and I have validated the content inside the function. The problem is that when I want to occupy that "handle" outside the function it always tells me that it is NULL, that makes me think that the problem is when I return from the function I am not correctly obtaining the content of the pointer. What would be the correct way to obtain it?

Upvotes: 2

Views: 58

Answers (1)

dbush
dbush

Reputation: 223972

In C, all function parameters are pass by value. That means any changes to the parameter handle in foo are not reflected in the calling function.

You should change foo to return a struct_handle * and assign that to handle in main.

Change the function to:

struct_handle *foo()
{
    enum com_ErrorCodes com_errno;
    struct_handle *handle;

    do
    {
        handle = com_Connect("val1", NULL, 10000, &com_errno);

        if(handle == NULL) 
        {
            //ERROR handle is NULL
        }
    }
    while(handle == NULL);

    return handle;
}

And call it like this:

handle = foo();

Upvotes: 4

Related Questions