带有指向自身指针的 C 结构 - 访问值

标签 c pointers struct

我对结构有疑问。我必须使用一个具有指向自身的指针的结构。我已经这样做了,我认为它有效:

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

我正在制作一个将子标签添加到标签的函数,例如“body”是 html 标签的子标签,所以我的程序核心转储并在我尝试时导致段错误使用子指针的“name”和“is_self_closing”变量。我不知道如何正确访问它们。这是程序的完整代码。

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

最佳答案

在您的 add_chilld() 函数中,您试图访问 parent->child 但您从未让它指向任何有效的东西。

因此,您正在取消引用一个未初始化的指针,该指针包含一个不确定的值,即无效的内存地址,这会导致 undefined behavior

换句话说,在你可以使用像parent->child->name这样的东西之前,你需要确保child成员>parent 变量实际上设置为某个 child(您之前分配的)。

关于带有指向自身指针的 C 结构 - 访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47981605/

相关文章:

c - 我在 mingw 中尝试了我的第一个程序。我得到以下输出。我的程序出了什么问题?

c - 指针和typedef结构,在C中调用函数时该怎么做

c - 直接寻址数组内存

Windows 中 JSON 文件的 C 库

c - 执行makefile时出现错误1

c - 如何从我的 64 位 gcc 机器为 32 位 gcc 机器创建二进制可执行文件?

c++ - 不复制 char 数组,函数 swap 不能正确编译并且 stringPtr 没有被修改

c - 为什么这段代码会出现指针错误?

pointers - 为什么 http.Client{} 的前缀是 &?

c - 嵌套结构 - 输入