【问题标题】:Struct value changes after accessing it twice两次访问后结构值发生变化
【发布时间】:2020-09-13 00:26:48
【问题描述】:

当我尝试从我的结构中访问年龄元素时(使用一个接受双指针的函数),我只能在第一次尝试时获得正确的值。为什么会发生变化?指针在移动吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct student {
    int age; 
    char name[200];
} student;


int getAge(student **s){
    int a = (*s)->age;
    return a;
}

student *create(){
    student st;
    student *mp = &st;
    st.age = 25;
    
    return mp;
}

int main()
{
    student *sp = create();
    int myAge = getAge(&sp);    
    printf("I am %d\n", myAge);
    int Age = getAge(&sp);
    printf("Again, I am %d\n", Age);
    
    return 0;
}

【问题讨论】:

    标签: function pointers struct


    【解决方案1】:

    我想我明白问题所在了。您的 create() 函数在堆栈上创建一个学生并设置 mp 指向它。当create() 函数返回时,(或可能在一段时间后)mp 指向任何地方,特别是因为它指向的堆栈帧已被破坏。

    请尝试使用malloc 在您的create 函数中创建学生:

    student *mp = malloc(sizeof student);
    

    或者如果这是 C++ 代码:

    student *mp = new student;
    

    完成后,请记住在main 函数中使用free(如果是C)或delete(C++)sp,以避免内存泄漏。

    【讨论】:

    • 感谢您的帮助,内森。不幸的是,它第二次仍然返回一个 10 位数字。我将 create() 函数更改为以下内容:
    • student *create(){ student st; st.age = 25; student *mp = malloc(sizeof(student)); mp = &amp;st; //student *mp = &amp;st; return mp; }
    • 删除mp = &amp;st; 行是否有效?也使用mp-&gt;age 而不是st.age 否则年龄将为0。
    • 删除 mp = &amp;st 导致两个查询的年龄 = 0。它确实修复了我在使用 free(sp) 时收到的无效指针错误。
    • 确保在调用malloc 之后设置mp-&gt;age = 25 以便返回的学生结构具有有效的年龄。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 2014-10-19
    • 1970-01-01
    • 2014-10-15
    • 2020-05-19
    • 1970-01-01
    • 2021-10-15
    相关资源
    最近更新 更多