Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does random_ints(a,N) do and how do I use it in my code? [closed]

Tags:

c++

cuda

http://developer.download.nvidia.com/CUDA/training/GTC_Express_Sarah_Tariq_June2011.pdf

In the above tutorial (slide 29), they initiate 3 pointers to ints:

int *a, *b, *c;

Clearly this is of type (int *), yet they somehow make it possible for the kernel to access its indices with syntax a[index]

They also use some (to me) unknown command to initialize their values:

a = (int *)malloc(size); random_ints(a, N);

So what does this command do? First it casts the pointer *a to point to an int (but later on a magically becomes a vector). I can't find any sources on what random_ints precisely does (and my compiler doesn't recognize it either because it probably requires some include). I guess it makes a a vector of length N with random ints (though a is of type int).

I tried working around this by doing the same thing with vector <int> * a; etc etc but I still have trouble passing that to my kernel (it won't add the elements no matter what I try).

I'm working in C++. Thanks in advance.

Edit: could this be pseudocode? Because the explicit C++ example does this in a different (comprehensible way)

like image 694
Jan M. Avatar asked Oct 21 '12 21:10

Jan M.


1 Answers

  • You can use pointer in C/C++ in the way like normal array. See:

Example

int* p = new int[2];
p[1] = 2;  
*(p + 1) = 2; // same as line above - just other syntax
*(1 + p) = 2; // and other way
 1[p] = 2; // don't use it - but still valid
  • You can allocate memory by malloc in C++ (it is derived from C way) but only for POD types, like int

Example

int* p = (int*)malloc(12 * sizeof(int)); // C way equivalent to C++: new int [12]

Be aware that you must free this pointer by free(p), not by delete [] p.

  • I guess the implementation of this function is just assigning N random numbers to int array represented by pointer:

Example:

void random_ints(int* a, int N)
{
   int i;
   for (i = 0; i < N; ++i)
    a[i] = rand();
}
like image 50
PiotrNycz Avatar answered Oct 19 '22 20:10

PiotrNycz