I'm trying to use a returned value of a thread. For that i just found the following article: How to return a value from thread in C
So I use the following Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *myThread()
{
int ret = 42;
// printf("%d\n", ret);
printf("%p\n",(void*)&ret);
void * ptr = (void*)&ret;
printf("%p\n", ptr);
printf("%d\n", *((int *)ptr));
return (void*) &ret;
}
int main()
{
pthread_t tid;
static void *status;
// int ret = 42;
// status = &ret;
// printf("%d\n", *((int *)status));
pthread_create(&tid, NULL, myThread, NULL);
pthread_join(tid, &status);
printf("%p\n",((int *)status));
printf("%d\n", *((int *)status));
return 0;
}
The outputs are: 0x7f7ead136f04, 0x7f7ead136f04, 42, 0x7f7ead136f04, 0
Why is the last value not 42?
Same Problem here:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* aufgabe_drei_thread() {
int i = 5;
return &i;
}
int main(int argc, char** argv) {
int* ptr_wert_aus_drei;
pthread_t thread_three_id;
pthread_create(&thread_three_id, NULL, aufgabe_drei_thread, NULL);
pthread_join (thread_three_id, &ptr_wert_aus_drei);
printf("Der Wert aus Thread 3 ist: %d\n", *((int *)ptr_wert_aus_drei));
return (EXIT_SUCCESS);
}
Output is: Der Wert aus Thread 3 ist: 32508 and not 5.
What am i doing wrong?