简体   繁体   中英

Value outside function doesn`t match inside function, C

Please, I got a problem and I need help.

Got struct (stack):

struct sAddress {
    tBSTNodePtr *data;
    struct sAddress *pointer_next;
}*ads_stack;

then I have PUSH function

void pushAds(tBSTNodePtr hodnota)
{
    struct sAddress *temp;
    temp = (struct sAddress*)malloc(sizeof(struct sAddress));
    temp->data = &hodnota;
    if (ads_stack == NULL) {
        ads_stack = temp;
        ads_stack->pointer_next = NULL;
    }
    else {
        temp->pointer_next = ads_stack;
        ads_stack = temp;
    }
    printf("PUSH ADS KEY: %s\n", ads_stack->data->Key->str);
}

When I push something (in tBSTNodePtr ofcourse) it will print value of Key->str properly. But when I try to printf the same outside the function like this:

printf("STACK DATA: %s\n", ads_stack->data->Key->str);

It will give me segfault (tried on Win 8.1 under codeblocks, and under Fedora using makefile). What I do wrong? Are pointers wrong? ads_stack is not NULL outside push function.

The problem is that

temp->data = &hodnota;

is refering to the address of the local variable hodnota (which is a param received).

could you explain what tBSTNodePtr is?

temp->data is a tBSTNodePtr * , and in your function you receive a tBSTNodePtr , not a tBSTNodePtr * . if you use &hodnota you will be referencing the address of the local parameter, when you leave your function it is out of scope, that variable doesn't exist anymore.

You should:

  • Pass a pointer to tBSTNodePtr
  • create a copy of hodnota inside your function

But maybe it all depends on what tBSTNodePtr is if it is a pointer to a BSTNode, then probably you should change other things. Probably changing the struct removing the * in data and changing temp->data = &hodnota; to temp->data = hodnota;

As a side note:

temp = (struct sAddress*)malloc(sizeof(struct sAddress));

The cast to struct sAddress * isn't mandatory in C. You can avoid it. Maybe something like:

temp = malloc(sizeof *temp);

looks better.

replace void pushAds(tBSTNodePtr hodnota) by void pushAds(tBSTNodePtr *hodnota) if you want to use hodnota struct to read parameter in your main function

but if you want to change hodnota struct you have to use void pushAds(tBSTNodePtr **hodnota) and then replace temp->data = &hodnota; by temp->data = *hodnota;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM