开发者

c size of one array to another

开发者 https://www.devze.com 2022-12-15 12:28 出处:网络
hi i have the following code... int *a, *b; int *d; int N = 2000; size_t size = N*sizeof(int); a = (int *) malloc(size);

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开发者_C百科 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) ?


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.


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;
}


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);
  ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消