警告:将/从/指针转换为不同大小的整数 [英] Warning: cast to/from pointer from/to integer of different size
本文介绍了警告:将/从/指针转换为不同大小的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习Pthreads。我的代码以我想要的方式执行,我可以使用它。但是它给了我编译时的警告。
I'm learning Pthreads. My code executes the way I want it to, I'm able to use it. But it gives me a warning on compilation.
我使用以下代码编译:
I compile using:
gcc test.c -o test -pthread
使用GCC 4.8.1。我得到了警告:
$ b
with GCC 4.8.1. And I get the warning
test.c: In function ‘main’:
test.c:39:46: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
pthread_create(&(tid[i]), &attr, runner, (void *) i);
^
test.c: In function ‘runner’:
test.c:54:22: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
int threadnumber = (int) param;
^
这个错误代码如下:
This error comes for the following code:
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#define MAX_THREADS 10
int sum; /* this data is shared by the thread(s) */
void *runner(void * param);
int main(int argc, char *argv[])
{
int num_threads, i;
pthread_t tid[MAX_THREADS]; /* the thread identifiers */
pthread_attr_t attr; /* set of thread attributes */
if (argc != 2) {
fprintf(stderr, "usage: test <integer value>\n");
exit(EXIT_FAILURE);
}
if (atoi(argv[1]) <= 0) {
fprintf(stderr,"%d must be > 0\n", atoi(argv[1]));
exit(EXIT_FAILURE);
}
if (atoi(argv[1]) > MAX_THREADS) {
fprintf(stderr,"%d must be <= %d\n", atoi(argv[1]), MAX_THREADS);
exit(EXIT_FAILURE);
}
num_threads = atoi(argv[1]);
printf("The number of threads is %d\n", num_threads);
/* get the default attributes */
pthread_attr_init(&attr);
/* create the threads */
for (i=0; i<num_threads; i++) {
pthread_create(&(tid[i]), &attr, runner, (void *) i);
printf("Creating thread number %d, tid=%lu \n", i, tid[i]);
}
/* now wait for the threads to exit */
for (i=0; i<num_threads; i++) {
pthread_join(tid[i],NULL);
}
return 0;
}
/* The thread will begin control in this function */
void *runner(void * param)
{
int i;
int threadnumber = (int) param;
for (i=0; i<1000; i++) printf("Thread number=%d, i=%d\n", threadnumber, i);
pthread_exit(0);
}
如何解决此警告?
How can I fix this warning?
推荐答案
。在很多系统上, sizeof(long)== sizeof(void *)
。
一个更好的主意可能是使用 intptr_t
。
A better idea might be to use intptr_t
.
int threadnumber = (intptr_t) param;
和
pthread_create(&(tid[i]), &attr, runner, (void *)(intptr_t)i);
这篇关于警告:将/从/指针转换为不同大小的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文