我一直在尝试使用以下代码和接受结构并返回指向它的指针的函数从函数返回指向结构的指针:
#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
是分配在不同位置的 tag
的副本,该位置是函数的堆栈帧,当函数返回时它被销毁。
所以在打印的那一刻,你正在打印释放的 struct
,这是未定义的行为。如果你希望你的代码出于任何原因工作,试试这个
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()
时,您在堆上分配了 struct
,数据将在任何可访问的地方有效1 直到您手动销毁它与 free()
一起使用,free()
函数将简单地释放内存 它不关心稍后会用它做什么,它只是将它返回到哪里它来自。
此外,始终检查 malloc()
的返回值。
1只要有一个指针保存由 malloc()
返回的原始内存地址。当您决定不再需要 struct
时,这正是您必须传递给 free()
的地址。
关于c - 从函数返回指向结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34815049/