加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

从函数返回指向结构的指针

发布时间:2020-12-16 10:36:08 所属栏目:百科 来源:网络整理
导读:我一直在尝试使用以下代码返回一个指向函数结构的指针,该函数接受一个结构并返回一个指向它的指针: #includestdio.h#includestdlib.h#includestring.hstruct mystruct{ int id; char name[10];};//this is the functionstruct mystruct *return_pointer(str
我一直在尝试使用以下代码返回一个指向函数结构的指针,该函数接受一个结构并返回一个指向它的指针:

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

struct mystruct
{
    int id;
    char name[10];
};


//this is the function
struct mystruct *return_pointer(struct mystruct a)
{
    struct mystruct *ptr;
    ptr = &a;
    return ptr;
}

int main()
{
    struct mystruct tag,*p;
    tag.id = 12;
    strcpy(tag.name,"abcd");

    printf("Values are: %dt%s",tag.id,tag.name);
    p=return_pointer(tag);

    printf("nValues through pointer: %dt%s",p->id,p->name);
    return 0;
}

但是当我尝试使用返回的指针访问结构的值时,它无法正常工作.它只显示’id’而不是’name’.
这可能是什么问题?
我已经在一本书中读过,该书曾说过在函数体中使用它:

ptr = (struct mystruct *)malloc(sizeof(struct mystruct));
ptr-> id = a.id; 
strcpy(p->name,a.name); 
//struct 'a' is argument to function

return ptr;

如果这是正确的解决方案那么为什么呢?

解决方法

因为您要从您传递的副本返回a副本. c中的参数按值传递,因此a是在不同位置分配的标记的副本,该位置是函数的堆栈帧,并在函数返回时被销毁.

因此,在打印时,您正在打印解除分配的结构,这是未定义的行为.如果您希望代码无论出于何种原因都能正常运行

struct mystruct *
return_pointer(struct mystruct *a)
{
    return a;
}

并在main()中将其更改为

p = return_pointer(&tag);
//                 ^ Pass the address of tag and return it
//                   the same as
//                    
//                                   p = &tag;
//
//                   which is why they say it's pointless in
//                   the comments

当你使用malloc()在堆上分配结构时,数据在任何可访问的地方都是有效的,直到你用free()手动销毁它,free()函数将简单地释放它不关心将要做什么的内存稍后,它只是将它回到它的来源.

另外,总是检查malloc()的返回值.

1,有一个指针保存malloc()最初返回的内存地址.当你决定不再需要struct时,这正是你必须传递给free()的地址.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读