views:

134

answers:

3

hi i have the following code...

  int *a, *b;
  int *d;
  int N = 2000;
  size_t size = N*sizeof(int);

  a = (int *) malloc(size);
  b = (int *) malloc(size);
  ...
  cudaMalloc((void **) &d, size);

it works just fine... now assume i have the following

  char **t = malloc(2000* sizeof *t);
  for(...)
  {
   ...
   t[i] = (char *)malloc(sizeof(char)*changing_length);
   ...
  }

how to do cudaMalloc for t as if it is one dimensional array (taking into account that each element has different size) ?

+1  A: 

If you have a regular 2D array of chars you can calculate the size with...

width * height * sizeof(char)

If you have an irregular 2D array (some rows have different lengths) then you'll have to either keep track of the total number of chars somewhere else or loop through and count how many chars you have before you do the cudaMalloc.

Pace
so you mean if for example i have 200 elements, and total number of chars of all of theses elements let's say equals N, then size_t size = 200*N*sizeof(char); ?
asel
I think so. I'm thinking of a 1024x1024 digital picture. It has 1024 rows and each row has 1024 elements. The total number of elements is 1024*1024.
Pace
let' say i have the following picture where my array has only three elements. a[0] stores 15 chars, a[1] stores 3 chars, and a[2] stores 5 chars. So the total number of elements becomes 15+3+5. Is it? Or is it (15+3+5)*sizeof(char)?
asel
It's the latter, (15 + 3 + 5)*sizeof(char)
Pace
thanks thanks a lot!
asel
if the length of elements varies, then sizeof(char) * width * height doesn't work.
John Knoeller
A: 

If I understand you correctly, you just need to malloc the SUM of all the smaller mallocs

char** t = malloc(2000 * sizeof(*t) + sizeof(char)*sum_of_changing_lengths);

Then setup t[x] to point to later parts of the allocation

char *p = (char*)(&t[2000]);
for (...)
{
   t[i] = p;
   p += changing_length;
}
John Knoeller
A: 

I think you are looking on how to get the address of the pointer t[i]. Since I am not sure about the evaluation order I would try &(t[i]), however, &t[i] should work too. If both do not work you have to calc the pointer position yourself. It will be something like &t + i*sizeof *t

char **t = malloc(2000* sizeof *t);
for(...)
{
  ...
  cudaMalloc((void **) &(t[i]), sizeof(char)*changing_length);
  ...
}
Peter Schuetze