首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >包含两个双指针的结构,访问第二个双指针时会出现seg错误

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

Stack Overflow用户
提问于 2019-10-20 10:10:10
回答 1查看 66关注 0票数 0

我试图访问第二个双指针,但它只有在访问第一个双指针后才会立即出现故障。怎么一回事?

它似乎在没有第二个双指针的情况下可以工作,但我不知道为什么。

代码语言:javascript
复制
#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

编辑:

它似乎仍然不起作用。我已经将以下代码添加到函数中:

代码语言:javascript
复制
    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:这似乎是可行的。

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-20 10:15:34

一旦函数退出,指向函数的局部变量的指针就不再有效,但是您的funct1函数会将这些指针保存在以后要使用的地方。特别是,在funct1返回后同时访问*(hello.x)*(hello.y)是无效的,并且第一种方法只能巧合地工作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58469503

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档