结构体作为函数返回值问题

tomsheep 2008-10-11 06:29:46
想用一个函数返回一个结构体
发现如果结构体内全都是基础类型时,不存在问题
但如果结构体内有指针的话,就会有问题

#include<stdio.h>
typedef struct test{
int a;
int b;
}test;

typedef struct test2{
int a;
int *b;
}test2;

test get(){
test t={3,4};
return t;
}
test2 get2(){
int a=8;
test2 t={7,&a};
return t;
}
int main(void){

int a=6;

test t1={1,2};
test t2=get();

test2 t3={5,&a};
test2 t4=get2();

printf("t1 %d %d\n",t1.a,t1.b);
printf("t2 %d %d\n",t2.a,t2.b);
printf("t3 %d %d\n",t3.a,*t3.b);
printf("t4 %d %d\n",t4.a,*t4.b); //*t4.b不对
return 0;
}


原因也能想明白,因为栈中的变量会释放掉
可要是想要返回一个含指针的结构体,该怎么解决?
...全文
1724 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
hackxq 2008-10-11
  • 打赏
  • 举报
回复
不好意思,借楼主的地方我再问一下
楼上有的高手说在堆上分配空间给t.b,楼主也说是因为函数调用完毕,栈中变量被释放了。
我有个地方不明白。
比如像下面这样,只对一个结构体实例化,就不会有问题。

#include <stdio.h>

typedef struct{
int a;
int *b;
}t;

t get(){
int c=2;
t tt={1,&c};
return tt;
}

main(){
t t1=get();
printf("%d %d",t1.a,*t1.b);//这里会正确输出

return 0;
}

这是何故?
HeReComes 2008-10-11
  • 打赏
  • 举报
回复
解决的不错,大家要多多帮助
HeReComes 2008-10-11
  • 打赏
  • 举报
回复
解决的不错
tomsheep 2008-10-11
  • 打赏
  • 举报
回复

看到了~
谢谢~
lzr4304061988012 2008-10-11
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 tomsheep 的回复:]
谢谢了~
那再弱问一下,像5楼这么做用不用free那快malloc的内存?
如果用,怎么free?
[/Quote]
肯定要的,

int main(void)
{

int a=6;

test t1={1,2};
test t2=get();

test2 t3={5,&a};
test2 t4=get2();

printf("t1 %d %d\n",t1.a,t1.b);
printf("t2 %d %d\n",t2.a,t2.b);
printf("t3 %d %d\n",t3.a,*t3.b);
printf("t4 %d %d\n",t4.a,*t4.b);
free(t4.b);//这里已经free了..........
return 0;
}


tomsheep 2008-10-11
  • 打赏
  • 举报
回复
谢谢了~
那再弱问一下,像5楼这么做用不用free那快malloc的内存?
如果用,怎么free?
frank_ll 2008-10-11
  • 打赏
  • 举报
回复
用C++类的话,你应该知道有一个叫拷贝函数的东西可以解决问题
但是返回指针的话更好,避免拷贝大量数据,节约时间
lzr4304061988012 2008-10-11
  • 打赏
  • 举报
回复
1L对了?
b指向的内存分配了?
cxxer 2008-10-11
  • 打赏
  • 举报
回复


#include<stdio.h>

typedef struct test
{
int a;
int b;
}test;

typedef struct test2
{
int a;
int *b;
}test2;

test get()
{
test t={3,4};
return t;
}

test2 get2()
{
test2 t;
t.a = 7;
t.b = (int *)malloc(sizeof(int)); //分析在堆中
*(t.b) = 8;
return t;
}
int main(void)
{

int a=6;

test t1={1,2};
test t2=get();

test2 t3={5,&a};
test2 t4=get2();

printf("t1 %d %d\n",t1.a,t1.b);
printf("t2 %d %d\n",t2.a,t2.b);
printf("t3 %d %d\n",t3.a,*t3.b);
printf("t4 %d %d\n",t4.a,*t4.b);
free(t4.b);
return 0;
}

帅得不敢出门 2008-10-11
  • 打赏
  • 举报
回复
我晕 怎么多回了一次
帅得不敢出门 2008-10-11
  • 打赏
  • 举报
回复
test2结构体中的指针b是浅拷贝 所以会出现问题
1楼的方法可行,但是用完要记得free掉

如果是c++的话 可以用class 做个深拷贝
lzr4304061988012 2008-10-11
  • 打赏
  • 举报
回复

test2 get2(){
int * a=new int(8);
test2 t={7,a};
return t;
}
//只针对此题,一般是要写个拷贝构造函数的.
wuyu637 2008-10-11
  • 打赏
  • 举报
回复
test2 *t = (test2*)malloc(sizeof(test2));

t.a = 1;
t.b = 1;


return t;

用指针。。

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧