简体   繁体   English

如何访问结构指针内的空指针的内容?

[英]How to access the content of a void pointer inside a struct pointer?

I have a struct pointer, that points to a struct that has a void pointer as it member, and I need to access the value of this member.我有一个结构指针,它指向一个结构,该结构具有一个空指针作为它的成员,我需要访问这个成员的值。

This is the struct with the void pointer I need access这是我需要访问的带有空指针的结构

typedef struct {
    void *content;
} st_data;

This is the function to create the struct, it returns a pointer to the struct这是创建结构的function,它返回一个指向结构的指针

st_data *create_struct(void *content)
{
    st_data *new;
    new = malloc(sizeof(st_data));
    new->content = content;
    return new;
}

I cant find the right syntax to print the value of the void pointer.我找不到正确的语法来打印 void 指针的值。

int main()
{
    int *number;
    *number = 10;
    st_data *new_struct = create_struct(number);
    
// just want to print the value of the void pointer 
    printf("%d\n", *(int *)new_struct->content);
    return 0;
}

@pmacfarlane's comment is more important (IMHO), but this will print the value of the pointer (as opposed to what it points to , as your code does): @pmacfarlane 的评论更重要(恕我直言),但这将打印指针的值(而不是它指向内容,就像您的代码那样):

printf("%p\n", new_struct->content);

You declare a pointer to an int, but it doesn't point to anything:你声明了一个指向 int 的指针,但它没有指向任何东西:

int *number; // Doesn't point to anything

You then de-reference this pointer, which leads to undefined behaviour:然后取消引用此指针,这会导致未定义的行为:

*number = 10; // BUG - undefined behaviour

You need to actually define a variable to store your number 10, and pass the address of that to your 'constructor':您实际上需要定义一个变量来存储您的数字 10,并将其地址传递给您的“构造函数”:

int number = 10;
st_data *new_struct = create_struct(&number);

Note that while this will work in your simple example, if your 'new_struct' structure outlived this function you'd have a problem, since the 'content' pointer points to something allocated on the stack, which would disappear if the function exited.请注意,虽然这将在您的简单示例中起作用,但如果您的“new_struct”结构比这个 function 长,您就会遇到问题,因为“content”指针指向堆栈上分配的内容,如果 function 退出,它就会消失。

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

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