C 从函数返回指向结构的指针
我一直在尝试使用以下代码和函数从函数返回指向结构的指针,该函数接受结构并返回指向结构的指针:C 从函数返回指向结构的指针,c,pointers,structure,C,Pointers,Structure,我一直在尝试使用以下代码和函数从函数返回指向结构的指针,该函数接受结构并返回指向结构的指针: #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)
#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;
}
如果这是正确的解决方案,为什么 因为您返回的
a
是您传递的副本。中的参数是通过值传递的,因此a
是分配在不同位置的标记的副本,该位置是函数的堆栈帧,当函数返回时,它将被销毁
因此,在打印时,您正在打印解除分配的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()
原始返回的内存地址。这正是当您决定不再需要结构时必须传递给free()
的地址。您应该这样做:
p = &tag;
指向相同的结构标记
。不要这样做:
p = return_pointer(tag);
因为当你传递标记时,你通过值传递它,它创建了一个副本(在函数返回指针中称为a
),因此,你的标记和a
(具体来说,它们的地址(即&tag
和&a
)是不同的-参见Caleb先生的评论)函数中的参数不同。函数参数是函数的局部变量。函数完成其工作后,它们将被销毁
您试图做的是通过引用传递一个结构并返回对它的引用。在这种情况下,函数将如下所示
//this is the function
struct mystruct * return_pointer( struct mystruct *ptr )
{
return ptr;
}
打电话给我
p = return_pointer( &tag );
虽然这样一个函数没有多大用处。不过,一般来说,它可能会更改所传递对象的某些数据成员。我是来自中国的代码初学者,您的代码的错误在于局部变量的域(ptr是指针)仅在函数中有效,但当您将其返回到全局主函数时,它所指向的内存已被释放。所以它变成了一个错误。很高兴回答你的问题 返回指针的作用是什么?这似乎毫无意义。@MichaelWalz别故意去!但实际上,只要p=&tag
就可以了。@Caleb,我知道,请看最后的答案。对不起,错过了你的评论,但是如果我们都说10到12次,消息就会被传递出去。;-)具体来说,&tag
和&a
将有不同的值。@Caleb啊,是的,你说得对。这更准确。这样的函数没有多大用处。。。我可以想到一些,包括一个调用一个库的应用程序,该库为一个网络的多个订阅提供服务,在这个网络中,对库的简单调用可以将信息传递给库,并通过struct*
更新应用程序。不过,这是一个很好的答案。
p = return_pointer( &tag );