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

时间:2016-01-15 16:00:16

标签: 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)
{
    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;
}

但是当我尝试使用返回的指针访问结构的值时,它无法正常工作。它只显示&#39; id&#39;但不是&#39;名称&#39;。 这可能是什么问题? 我已经在一本书中读过,该书曾说过在函数体中使用它:

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

return ptr;

如果这是正确的解决方案那么为什么呢?

4 个答案:

答案 0 :(得分:7)

因为您要返回的def exit(): print("Shutting down.") if __name__ == '__main__': choices = { "1" : createPerson , "2" : searchPerson, "3": exit } x = '1' while x != "3": print(' (1) Create new person') print(' (2) Search for a person') print(' (3) Quit') x = input('Select an option -> ') if x not in ['1', '2', '3']: print('Please choose one of the available options.') continue choices[x]() 是您传递的副本。 中的参数按值传递,因此a是在不同位置分配的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()时,数据将在任何可访问的 1 处有效,直到您使用struct手动销毁它为止, free()函数将简单地释放内存,它不关心以后会用它做什么,它只是将它返回到它的来源。

此外,始终检查free()的返回值。

1 只要有指针保存malloc()原始返回的内存地址。当您确定不再需要malloc()时,这正是您必须传递给free()的地址。

答案 1 :(得分:4)

你应该这样做:

p = &tag;

指向相同的结构tag。不要这样做:

p = return_pointer(tag);

因为当您传递tag时,您会按值传递它并创建一个副本(在函数a中称为return_pointer),因此,taga(具体地说,那些(&tag&a)的地址不同 - 参见Caleb先生的评论)在函数中是不一样的。

答案 2 :(得分:2)

函数参数是函数的局部变量。它们在函数完成工作后被销毁。

您要做的是通过引用传递结构并返回对它的引用。在这种情况下,函数看起来像

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

并调用

p = return_pointer( &tag );

虽然这种功能没有用处。然而,一般来说,它可以例如更改传递对象的一些数据成员。

答案 3 :(得分:0)

我是来自中国的代码初学者,你的代码的错误是局部变量的域(ptr是一个指针)只在函数中有效,但当你将它返回到你的全局主函数时,它指向已被释放的记忆。所以它变成了一个错误。我很高兴回答你的问题!

相关问题