首页 > 解决方案 > 在 C 中,我无法获取成员结构(双指针)的指向值。该值在分配该值的函数之外丢失

问题描述

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

typedef struct {
  double *presult;
} SomeData;

//Fonction that assigns the value to be pointed
void  *assignValue(void *data) {
    SomeData *aData = (SomeData*)data;
    double valeurTotal = 45.50;

    aData->presult = &valeurTotal; //Make the pointer point to the value

    printf("%10.3f \n",*aData->presult); //Here it prints the right answer L 45.50
    pthread_exit(NULL);
}

int main(int argc, char *argv[]) {
    SomeData myData; // The struct
    pthread_t onethread; 
    pthread_create(&onethread, NULL, assignValue,(void *)&myData); 
    pthread_join(onethread, NULL);

    printf("**************************************** \n");
    printf("%10.3f \n", (myData.presult)); // prints: 0
    printf("%10.3f \n", *(myData.presult));// prints: 0

    exit(0);
}

问题可能会令人困惑,所以希望我的代码的这个简化版本可以更好地解释。所以基本上,我创建了一个修改结构值的线程。

在线程函数内部,结构体作为指针传递。结构的成员之一是双指针“presult”。线程函数使'presult'指向一个值,它似乎工作,因为打印工作。

然而,回到主函数,我尝试再次打印“presult”的值,但它没有打印 45.50,而是 0.0。

在我的完整代码中,我实际上在最后一次打印时遇到了分段错误。但即使在这个简化的代码中,它也不起作用。它不打印 45.50。

输出如下:

45.50
****************************************
0.000
0.000

任何帮助表示赞赏。谢谢你。

标签: cpointers

解决方案


double valeurTotal = 45.50;
aData->presult = &valeurTotal; //Make the pointer point to the value

当超出范围时,分配给的内存位置valeurTotal将被重用。assignValue

这很可能是在

printf("%10.3f \n", *(myData.presult)); // prints: 0

同样在这一行,您尝试将指针打印为浮点数,这很古怪。

printf("%10.3f \n", (myData.presult)); // prints: 0

您需要将值实际存储在结构中,您可以通过

typedef struct {
  double presult; // will copy into this when its assigned.
} SomeData;

显然,如果您只想要一个双精度值,您只需将该双精度值作为指针而不是结构传递。


推荐阅读