Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();

}
like image 259
Programmer Avatar asked Jan 22 '26 23:01

Programmer


1 Answers

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]);
}
like image 183
Jared Hoberock Avatar answered Jan 26 '26 00:01

Jared Hoberock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!