包含两个双指针的结构,访问第二个双指针时出现段错误

A struct that contains two double pointers, seg faults when accessing second double pointer

我正在尝试访问第二个双指针,但它仅在访问第一个双指针后立即出现段错误。怎么回事?

它似乎没有第二个双指针也能工作,但我不知道为什么。

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

struct queue{
    int ** x;
    int ** y;
};

struct queue funct1(){
    struct queue me;
    int * x = malloc(sizeof(int));
    int * y = malloc(sizeof(int));

    *x = 20;
    *y = 40;
    me.x = &x; 
    me.y = &y;
    return me;
}


int main(void){
    struct queue hello;

    hello = funct1();

    printf("%d\n", *(*(hello.x)));
    printf("%d\n", *(*(hello.y)));
}

预计: 20 40

实际: 20 分段错误:11

编辑:

好像还是不行。我已将此代码添加到函数中:

    int ** xpointer = malloc(sizeof(int*));
    int ** ypointer = malloc(sizeof(int*));

    *x = 20;
    *y = 40;
    xpointer = &x;
    ypointer = &y;

    me.x = xpointer; 
    me.y = ypointer;

编辑 2:这似乎有效。

struct queue funct1(){
    struct queue me;
    int * x = malloc(sizeof(int));
    int * y = malloc(sizeof(int));

    int ** xpointer = malloc(sizeof(int*));
    int ** ypointer = malloc(sizeof(int*));

    *x = 20;
    *y = 40;
    *xpointer = x;
    *ypointer = y;

    me.x = xpointer; 
    me.y = ypointer;

    return me;
}

函数退出后,指向函数局部变量的指针将不再有效,但您的 funct1 函数会将此类指针保存在稍后会用到的地方。特别是,在 funct1 returns 之后同时访问 *(hello.x)*(hello.y) 是无效的,而且第一个有效只是巧合。