微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我一直在尝试使用以下代码返回一个指向函数结构的指针,该函数接受一个结构并返回一个指向它的指针:

#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: %d\t%s",tag.id,tag.name);
    p=return_pointer(tag);

    printf("\nValues through pointer: %d\t%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()的地址.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐