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

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

#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()的地址.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...