'Weird behavior when casting void*
I'm trying to create threads in c and I had to pass an argument to threadRunFunction
but I stumbled upon some warnings.
First prototype (Doesn't contain warnings when compiling it and when using long int):
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define CHECK(func, msg) if ((func)) fprintf(stderr, "ERROR: %s\n", msg);
#define N_THREADS 10
pthread_t thread[N_THREADS];
void* threadRunFunction(void *param) {
const long int thread_number = (long int) param;
printf("Thread #%ld running...\n", thread_number);
return NULL;
}
int main() {
for (long int i = 0; i < N_THREADS; i++) {
CHECK(pthread_create(&thread[i], NULL, threadRunFunction, (void*)i), "pthread_create");
}
for (int i = 0; i < N_THREADS; i++)
CHECK(pthread_join(thread[i], NULL), "pthread_join");
return EXIT_SUCCESS;
}
Second protype (Contain warnings when compiling it and when using int instead of long int):
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define CHECK(func, msg) if ((func)) fprintf(stderr, "ERROR: %s\n", msg);
#define N_THREADS 10
pthread_t thread[N_THREADS];
void* threadRunFunction(void *param) {
const int thread_number = (int) param;
printf("Thread #%d running...\n", thread_number);
return NULL;
}
int main() {
for (int i = 0; i < N_THREADS; i++) {
CHECK(pthread_create(&thread[i], NULL, threadRunFunction, (void*)i), "pthread_create");
}
for (int i = 0; i < N_THREADS; i++)
CHECK(pthread_join(thread[i], NULL), "pthread_join");
return EXIT_SUCCESS;
}
These are the warning messages of the second prototype:
main2.c: In function ‘threadRunFunction’:
main2.c:12:29: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
12 | int thread_number = (int) param;
| ^
main2.c: In function ‘main’:
main2.c:19:75: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
19 | CHECK(pthread_create(&thread[i], NULL, threadRunFunction, (void*)i), "pthread_create");
They both run correctly but I want to know the reason why the second one is throwing these warnings and the first one is not.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
