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

前端 未结 4 1176
故里飘歌
故里飘歌 2020-12-14 01:21

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          


        
相关标签:
4条回答
  • 2020-12-14 01:45

    I was also getting the same warning. So to resolve my warning I converted int to long and then this warning just vanished. And about the warning "cast to pointer from integer of different size" you can leave this warning because a pointer can hold the value of any variable because pointer in 64x is of 64 bit and in 32x is of 32 bit.

    0 讨论(0)
  • 2020-12-14 01:57
    pthread_create(&(tid[i]), &attr, runner, (void *) i);
    

    You are passing the local variable i as an argument for runner, sizeof(void*) == 8 and sizeof(int) == 4 (64 bits).

    If you want to pass i, you should wrap it as a pointer or something:

    void *runner(void * param) {
      int id = *((int*)param);
      delete param;
    }
    
    int tid = new int; *tid = i;
    pthread_create(&(tid[i]), &attr, runner, tid);
    

    You may just want i, and in that case, the following should be safe (but far from recommended):

    void *runner(void * param) {
      int id = (int)param;
    }
    
    pthread_create(&(tid[i]), &attr, runner, (void*)(unsigned long long)(i));
    
    0 讨论(0)
  • 2020-12-14 02:04

    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);
    
    0 讨论(0)
  • 2020-12-14 02:06

    Try passing

    pthread_create(&(tid[i]), &attr, runner, (void*)&i);
    
    0 讨论(0)
提交回复
热议问题