简体   繁体   English

通过 C 中的指针数组访问结构的成员

[英]Accessing members of a struct via an array of pointers in C

The second if statement in main does not print out. main 中的第二个 if 语句不会打印出来。 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.如果我只放置它们执行的 if 语句之一,但由于某种原因将它们放在一起会导致第二个 if 语句不打印任何内容。 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. new是一个自动变量。 It only exists while init_arr() is executing.它仅在init_arr()执行时存在。 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.一旦你离开 function,之前用于new的 memory 可能会用于其他一些事情,因此array[3]->keyarray[3]->value实际上都没有定义。

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.如果你得到array[3]->value的“正确”值只是因为如果第一个if被评估,那么用于new的 memory 仍然有可能还没有被回收,但它肯定已经被评估第二个if的时间。

If you need the memory used by new to be valid even after the function has exited, declare it static .如果您需要new使用的 memory 即使在 function 退出后仍然有效,请将其声明为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:或者为它分配 memory :

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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