Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

gcc - Warning: cast to/from pointer from/to integer of different size

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

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>
");
    exit(EXIT_FAILURE);
  }

  if (atoi(argv[1]) <= 0) {
    fprintf(stderr,"%d must be > 0
", atoi(argv[1]));
    exit(EXIT_FAILURE);
  }

  if (atoi(argv[1]) > MAX_THREADS) {
    fprintf(stderr,"%d must be <= %d
", atoi(argv[1]), MAX_THREADS);
    exit(EXIT_FAILURE);
  }

  num_threads = atoi(argv[1]);
  printf("The number of threads is %d
", 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 
", 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
", threadnumber, i);
  pthread_exit(0);
}

How can I fix this warning?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A quick hacky fix might just to cast to long instead of int. On a lot of systems, sizeof(long) == sizeof(void *).

A better idea might be to use intptr_t.

int threadnumber = (intptr_t) param;

and

pthread_create(&(tid[i]), &attr, runner, (void *)(intptr_t)i);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...