Search code examples
cudaprintfnvidiathrust

thrust::device_reference can't be used with printf?


I am using the thrust partition function to partition array into even and odd numbers. However, when i try to display the device vector, it shows random values. Please let me know where is the error. I think i have done everything correct.

#include<stdio.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include<thrust/partition.h>

struct is_even
  {
      //const int toCom;
      //is_even(int val):toCom(val){}
    __device__
    bool operator()(const int &x)
    {
      return x%2;
    }
  };

void main(){


    thrust::host_vector<int> H(6);
    for(int i =0 ; i<H.size();i++){
        H[i] = i+1;
    }
    thrust::device_vector<int> D = H;
    thrust::partition(D.begin(),D.end(),is_even());
    for(int i =0 ;i< D.size();i++){
        printf("%d,",D[i]);
    }


    getchar();

}

Solution

  • You can't send a thrust::device_reference (i.e., the result of D[i]) through printf's ellipsis because it is not a POD type. See the documentation. Your code will produce a compiler warning to this effect.

    Cast to int first:

    for(int i = 0; i < D.size(); ++i)
    {
      printf("%d,", (int) D[i]);
    }