Home > database >  Pointer not being set correctly in function
Pointer not being set correctly in function

Time:01-27

I have a code where I use a pointer

One of the functions is in file 1

In the main file I call the function of file 1

When I pass the pointer it is not being defined,

I get Test is NULL message

What is the correct way for me to use this?

my code:

File 1

struct mystruct {
    unsigned short id;
    int number;
    ....
}

struct mystruct *test_check(state *ck, char *name);

void GetMytest(state *ck, char *name, struct mystruct *test) {
        checkfield(ck, name);
        test = test_check(ck, name);
        .....
}

Main file

struct mystruct *test

void MainTest() {

    state *ck = check_new();
    .....

    GetMytest(ck, "Stats", test);
    
    if(test == NULL)
        printf("Test is NULL");

}

CodePudding user response:

The statement test = test_check(ck, name); in GetMytest only modifies the local argument variable test, not the global variable by the same name.

If you want to update the pointer in the calling scope (the MainTest function or the global scope), you must pass a pointer to this variable.

I do something similar in some of my code

Try as follows

File 1:

void GetMytest(state *ck, char *name, struct mystruct **test) {
        checkfield(ck, name);
        *test = test_check(ck, name);
        .....
}

Main function:

void MainTest() {

    state *ck = check_new();
    .....

    GetMytest(ck, "Stats", &test);
    
    if (test == NULL)
        printf("Test is NULL");
}

If the other functions are correct this should solve the problem.

  •  Tags:  
  • c
  • Related