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

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

问题描述

这个程序返回一个指向结构的指针.
当我打印内容时,name 没有正确显示,而其他两个变量正在正确打印.
可能是什么问题呢?这是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	 %d	 %d	",ptr->name,ptr->marks,ptr->rank);
}

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

推荐答案

这里的问题是你返回了一个指向 local 变量的指针.一旦返回定义局部变量的函数,局部变量就会超出范围.这意味着您返回的指针将在函数返回后指向未分配的内存.使用该指针将导致未定义的行为.

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天全站免登陆