c - 从结构指针打印间歇性失败

标签 c struct

<分区>

我设法将出现问题的代码浓缩为:

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

typedef struct
{
    double height;
    double hello;
}Variables;     

void information(Variables **Constants);
int main()
{
    Variables *Constants=NULL;
    information(&Constants);        //Assigns values to the structure pointer

    printf("Height %lf \n",Constants->height);          //These print correctly only
    printf("hello %lf \n",Constants->hello);           //intermittently 
    return(0);
}

void information(Variables **Constants)     //Assigns values structure pointer
{
    Variables *consts,constants;

    constants.height=10;
    constants.hello=20;

    consts=&constants;
    *Constants=consts;

    printf("Height %lf \n",constants.height);          //These always print correctly
    printf("hello %lf \n",constants.hello);   
    return;

}

据我了解,这段代码应该在 main 中创建一个结构指针,*Constants。然后使用 information(&Constants) 将该指针传递到函数中。在 information() 中创建了另一个指针并为其分配了一个结构变量。然后填充变量并将指针分配给 *Constants,然后允许将整个结构传递回 main()

如果我在 information() 中打印结构,则值是正确的。但是,如果我在 main() 中打印值,这些值有时是正确的,或者它们会打印随机数。如果您能帮助理解这一点,我们将不胜感激。

最佳答案

您正在从函数返回局部变量。这引起了问题。

当程序存在于函数 information() 中时,您在 main 中使用的变量 constants 的地址已经超出范围。
要解决此问题,您需要使用动态分配在函数 information() 中创建对象。并释放在 main 中动态分配的内存。

关于c - 从结构指针打印间歇性失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35896129/

相关文章:

c - 段错误(Core Dumped)--结构和指针--C语言

c - 如何重新初始化指向结构的指针而不删除其内存内容? (在C中)

java - 通过 JNI 将 C++ 类返回给 Java

c - 如何在 C 中检测/分析内存(堆、指针)读写?

c - 如何从 C 文件中读取 float

c++ - 生成唯一编号

html - 如何在C中转义html实体?

arrays - 有效过滤 MATLAB 结构数组?

c - 在C中动态创建sembuf结构

c - 使进程采取不同的行为取决于它是否收到来自另一个进程的消息?