[英]In C, I'm having trouble getting the pointed value of a member struct(a double pointer). The value is lost outside the function assigning the value
#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);
}
Question might be confusing, so hopefully this simplified version of my code can explain better. 问题可能令人困惑,因此希望我的代码的简化版本可以更好地解释。 So basically, I've created a thread that modifies the values of a struct.
因此,基本上,我创建了一个修改结构值的线程。
Inside the thread function, the struct is passed-on as a pointer. 在线程函数内部,该结构作为指针传递。 One of the struct's member is a double pointer 'presult'.
结构的成员之一是双指针“ presult”。 The thread function makes the 'presult' point to a value and it seems to work, because the print works.
线程函数使“结果”点指向一个值,并且它似乎起作用,因为打印有效。
However, back into the main function, I try to print the value of 'presult' again, but it doesn't print 45.50, but 0.0 instead. 但是,回到主函数中,我尝试再次打印'presult'的值,但是它不打印45.50,而是打印0.0。
In my full code, I actually get Segmentation fault with the last print. 在我的完整代码中,我实际上在上次打印时遇到了细分错误。 But even in this simplified code, it doesn't work.
但是,即使在这种简化的代码中,它也不起作用。 It doesn't print 45.50.
它不会打印45.50。
Output is as followed: 输出如下:
45.50
****************************************
0.000
0.000
Any help is appreciated. 任何帮助表示赞赏。 Thank you.
谢谢。
double valeurTotal = 45.50;
aData->presult = &valeurTotal; //Make the pointer point to the value
The memory location assigned to valeurTotal
is going to be reused when assignValue
goes out scope. 当
assignValue
超出作用域时,分配给valeurTotal
的内存位置将被重用。
This is most likely the case at 这很可能是
printf("%10.3f \n", *(myData.presult)); // prints: 0
Also at this line you're trying to print a pointer as a floating number, which is wacky. 同样在这一行,您尝试将指针打印为浮点数,这很奇怪。
printf("%10.3f \n", (myData.presult)); // prints: 0
You need to actually store the value in your structure, which you can do by 您需要将值实际存储在结构中,可以通过
typedef struct {
double presult; // will copy into this when its assigned.
} SomeData;
Obviously, if you only wanted one double value you'd just pass that double as a pointer rather than a strucutre. 显然,如果只需要一个double值,则只需将该double用作指针而不是strucutre。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.