I am writing host code for a CUDA program, so I am stuck using standard C functions. I am having a problem with initializing the elements of an integer array using the memset
function. I was under the impression you could use memset
to initialize an integer array to, for example, all 4s like this:
int num_elements = 10;
int* array_example = (int*)malloc(num_elements * sizeof(int));
memset(array_example, 4, sizeof(array_example));
But when I do this, it sets each byte, not each int
, to 4. If I say:
memset(array_example, 4, 1);
I get a 4 in the first integer and if I say:
memset(array_example, 4, 2);
I get 1024 in the first integer and 0 in the second. I understand the memset
function sets the number of bytes specified in the third parameter to 4, but is there any way to use memset to set each integer to 4 instead of each byte? Otherwise, am I stuck using a for loop? My GPU has a low compute capability so I don't have access to some of the nicer CUDA additions that allow more C++ usage.
If you know the size of a table and want to set each element to the certain value you can always write:
int array[10] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 };
If you use gcc you can also do this in this way:
int array[10] = {[0 ... 9] = 4};
When you have to dynamically allocate the array I doubt that there is any alternative solution then just using a simple loop.