简体   繁体   中英

Accessing members of a struct via an array of pointers in C

The second if statement in main does not print out. If I put just one of the if statements they do execute, but for some reason putting them after each other causes the second if statement to not print anything. Can anyone explain why this happens?

#include <stdio.h>
#include <stdlib.h>

typedef struct entry {
    int value;        
    char *key;
    int type;
} entry;

entry* array[5];

void init_arr(){
    for(int i=0; i<5; i++){
        array[i] = NULL;
    }

    entry new;
    new.value = 2;
    new.key = NULL;
    new.type = 5;
    array[3]= &new;
        
}

int main(){
    init_arr();

    if(array[3]->value == 2){
        printf("ok\n");
    }

    if(array[3]->key == NULL){
        printf("ok 2\n");
    }
    return 0;
}```

new is an automatic variable. It only exists while init_arr() is executing. As soon as you leave that function, the memory previously used for new may be used for some other thing, so both array[3]->key and array[3]->value are actually not defined.

If you get "right" values for array[3]->value is just because there is still a chance that memory used for new hasn't been already recycled by the time if first if is evaluated, but it has surely changed by the time the second if is evaluated.

If you need the memory used by new to be valid even after the function has exited, declare it static .

void init_arr()
{
    static entry new;

    for(int i=0; i<5; i++)
        array[i] = NULL;

    new.value = 2;
    new.key = NULL;
    new.type = 5;
    array[3]= &new;
}

Or allocate memory for it:

void init_arr()
{
    for(int i=0; i<5; i++)
        array[i] = NULL;

    array[3] = malloc(sizeof *array);     
    array[3].value = 2;
    array[3].key = NULL;
    array[3].type = 5;
}

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