c - 在 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
任何帮助表示赞赏。谢谢你。
解决方案
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;
显然,如果您只想要一个双精度值,您只需将该双精度值作为指针而不是结构传递。
推荐阅读
- reactjs - 使用 Docusign Clickwrap API 做出反应
- python - Codeforces 练习 71
- firebase - 展开时非 Nil 用户崩溃 - Firebase,SwiftUI
- javascript - 在 Vue.js v2.x 中使用 v-for 指令时,如何指定范围的起始值?
- ios - WKWebView在后台,几个奇怪的断言
- prolog - SWI-Prolog 检查不同列表中的两个元素是否不在同一位置。元素 1 应该在元素位置之前或之后
- multithreading - kotlin 中的 Thread.sleep 方法会阻塞线程吗?
- python - 尝试从搜索中运行程序时出现“执行脚本失败”错误
- python-3.x - MongoDB - 查询以获取每个项目的最新报价
- django - /add-to-cart/1/ 处的类型错误