我试图访问第二个双指针,但它只有在访问第一个双指针后才会立即出现故障。怎么一回事?
它似乎在没有第二个双指针的情况下可以工作,但我不知道为什么。
#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;
}发布于 2019-10-20 10:15:34
一旦函数退出,指向函数的局部变量的指针就不再有效,但是您的funct1函数会将这些指针保存在以后要使用的地方。特别是,在funct1返回后同时访问*(hello.x)和*(hello.y)是无效的,并且第一种方法只能巧合地工作。
https://stackoverflow.com/questions/58469503
复制相似问题