简体   繁体   中英

C struct with pointer to itself - accessing values

I have a problem with structs. I must use a struct that has a pointer to itself. I have done this and I think it works:

typedef struct tag_t tag_t;
    struct tag_t{
    char name[15];
    int is_self_closing;
    tag_t *child;
};

I am making a function that adds a child to a tag, like "body" is a child of the html tag, so my program core dumped and resulted in a segmentation fault when I tried to work with the "name" and "is_self_closing" variables of the child pointer. I don't know how to access them correctly. This is the entire code for the program.

#include <stdio.h>
#include <string.h>

typedef struct tag_t tag_t;
struct tag_t{
    char name[15];
    int is_self_closing;
    tag_t *child;
};

void add_chilld(tag_t *,char[15],int);

void print_markup(tag_t);

int main(int argc, char **argv){
    tag_t parent,child;
    strcpy(child.name,"body");
    child.is_self_closing = 1;
    strcpy(parent.name,"html");
    parent.is_self_closing = 0;
    add_chilld(&parent,child.name,child.is_self_closing);
    printf("child name = %s child closing = %d\n",child.name,child.is_self_closing);
    printf("%s %d %s\n",parent.name,parent.is_self_closing,parent.child->name);
    return 0;
}

void add_chilld(tag_t *parent,char name[15],int is_self_closing){
    if(is_self_closing == 1){
        printf("parent name = %s\n",parent->child->name);
        strcpy(parent->child->name,name);
        parent->child->is_self_closing = is_self_closing;
    }else{
        parent->child = NULL;
    }
}

Inside your add_chilld() function, you are attempting to access parent->child but you never made it point to anything valid.

So, you're dereferencing an uninitialized pointer, which holds an indeterminate value, ie, an invalid memory address, which causes undefined behavior

In other words, before you can make use of something like parent->child->name , you need to make sure that the child member of the parent variable is actually set to some child (which you allocated earlier).

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