返回指向C中的结构的指针 [英] returning pointer to a structure in C

查看:201
本文介绍了返回指向C中的结构的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此程序返回指向结构的指针

当我打印内容时,名称未正确显示,其中其他两个变量正在正确打印。

可能是什么问题?
这里是C中的代码

this program returns a pointer to a structure.
When i print the contents, the name is not being displayed properly, where as the other two variables are being properly printed.
What could be the problem? Here is the code in C

#include<stdio.h>
struct student
    {
        char name[20];
        int marks;
        int rank;
    };
struct student stu;
struct student *create();

void main()
{
    struct student *ptr;
    ptr = create();
    printf("%s\t %d\t %d\t",ptr->name,ptr->marks,ptr->rank);
}

struct student *create()
{
    struct student stu = {"john",98,9};
    struct student *ptrr;
    ptrr = &stu;
    return ptrr;
}


推荐答案

'返回一个指向 变量的指针。一旦它们定义的函数返回,局部变量就超出范围。这意味着返回的指针将在函数返回后指向未分配的内存。使用该指针将导致 未定义的行为

The problem here is that you're returning a pointer to a local variable. Local variables goes out of scope once the function they are defined in returns. That means that the pointer you return will point to unallocated memory after the function returns. Using that pointer will lead to undefined behavior.

有三种方法可以解决这个问题:

There are three ways to solve this:


  1. 使用全局变量,并返回一个指针。全局变量的生命周期是程序的生命周期。

  2. 使用 static 局部变量。

  3. 在需要时动态分配结构,并返回该指针。

  1. Use a global variable, and return a pointer to that. The lifetime of a global variable is the lifetime of the program.
  2. Use a static local variable. It also will have the lifetime equal to the program.
  3. Allocate the structure dynamically when needed, and return that pointer.

点1和点2有一个问题,那就是你只能有一个对象。如果你修改那个对象,你有指向该单个对象的指针的所有地方都会看到这些变化。

Points 1 and 2 have a problem in that then you can only have a single object. If you modify that object, all places where you have a pointer to that single object will see those changes.

点3是我推荐你去的方式。问题是,一旦你完成了对象,你必须释放你分配的内存。

Point 3 is the way I recommend you go. The problem with that is that once you're done with the object, you have to free the memory you allocate.

这篇关于返回指向C中的结构的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆