简体   繁体   English

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

[英]Returning a pointer to structure from a function

I have been trying to return a pointer to a structure from a function using the following code and a function which accepts a structure and returns a pointer to it : 我一直在尝试使用以下代码返回一个指向函数结构的指针,该函数接受一个结构并返回一个指向它的指针:

#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;
}

but when i try to access the structure's values using the returned pointer, its not working properly. 但是当我尝试使用返回的指针访问结构的值时,它无法正常工作。 It is only displaying the 'id' but not the 'name'. 它只显示'id'而不是'name'。 What can be the possible problem here? 这可能是什么问题? I have read in a book which said to use this in function's body: 我已经在一本书中读过,该书曾说过在函数体中使用它:

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

return ptr;

If this is the correct solution then why so? 如果这是正确的解决方案那么为什么呢?

Because you are returning the a that is a copy from the one you passed. 因为你是返回a不是您传递的一个副本。 Parameters in are passed by value, thus a is a copy of tag allocated in a different place, that place is the stack frame of the function and it is destroyed when the function returns. 中的参数按值传递,因此a是在不同位置分配的tag的副本,该位置是函数的堆栈帧,并在函数返回时被销毁。

So at the moment of printing you are printing the deallocated struct , and that is undefined behavior. 因此,在打印时,您正在打印解除分配的struct ,这是未定义的行为。 If you want your code to work for whatever reason try this 如果您希望代码无论出于何种原因都能正常运行

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

and in main() change it to 并在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

When you use malloc() you allocate the struct on the heap, the data will be valid wherever accessible 1 until you manually destroy it with free() , the free() function will simply release the memory it doesn't care what will be done with it later, it just gives it back to where it came from. 当你使用malloc()在堆上分配struct时,数据在任何可访问的地方都是有效的1,直到用free()手动销毁它, free()函数将简单地释放它不关心什么的内存稍后完成它,它只是将它返回到它的来源。

Also, ALWAYS check the return value of malloc() . 另外,总是检查malloc()的返回值。


1 Wherever there is a pointer holding the address of the memory originaly returned by malloc() . 1 只要有指针保存malloc()最初返回的内存地址。 This is exactly the address that you MUST pass to free() when you decide that you don't need the struct anymore. 当你决定不再需要struct时,这正是你必须传递给free()的地址。

You should do this instead: 你应该这样做:

p = &tag;

To point to the same structure tag . 指向相同的结构tag Don't do this: 不要这样做:

p = return_pointer(tag);

Because when you pass the tag , you pass it by value and it creates a copy (which is called a in the function return_pointer ) thus, your tag and a (specifically, the addresses of those (that is &tag and &a ) are different - See Mr. Caleb's comment) in the function is not the same. 因为当你传递tag ,你按值传递它并创建一个副本(在函数return_pointer称为a ),因此,你的taga (具体地说,那些地址(即&tag&a )是不同的 -见Caleb先生的评论)在功能上是不一样的。

Function parameters are the function's local variables. 函数参数是函数的局部变量。 They are destroyed after the function finishes its work. 它们在函数完成工作后被销毁。

What you are trying to do is to pass a structure by reference and return the reference to it. 您要做的是通过引用传递结构并返回对它的引用。 In this case the function will look like 在这种情况下,该功能将如下所示

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

and called like 并称之为

p = return_pointer( &tag );

Though there is no great usefulness of such a function. 虽然这种功能没有用处。 Nevertheless in general it could for example change some data members of the passed object. 然而,通常它可以例如改变传递的对象的一些数据成员。

I am a code-beginner from china,the error of your code is that the domain of local variable (ptr which is a pointer) is only effective in the function,but when your return it to your global main function,the memory which it point to have been freed. 我是来自中国的代码初学者,你的代码的错误是局部变量的域(ptr是一个指针)只在函数中有效,但当你将它返回到你的全局主函数时,它的内存就是它指向已被释放。 so it turn into a error. 所以它变成了一个错误。 MY PLEASURE TO ANSWER YOUR ! 我很高兴回答你的问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM