Reputation: 315
I want to swap two arrays within an opencl-c call in that manner:
uint tmp_a[L] = {...};
uint tmp_b[L] = {...};
swap(tmp_a, tmp_b); // (tmp_a, tmp_b) <- (tmp_b, tmp_a)
I would like to do it just by swapping the base addresses of the two pointers, but unfortunatley
void swap(uint num_a[L], uint num_b[L]) {
uint* tmp = num_a;
num_a = num_b;
num_b = tmp;
}
doesn't work.
In reality I do it now this way:
for(int i = 0; i < L; ++i) {
const uint tmp = num_a[i];
num_a[i] = num_b[i];
num_b[i] = tmp;
}
I would like to reduce this unnecessary work.
Upvotes: 0
Views: 826
Reputation: 9925
An array is just a pointer to a chunk of memory. When you pass an array to a function (as in your code snippet), you are passing the value of that pointer to the function. Passing an argument to a function is much like an assignment operation. Consider this simple example:
void foo(uint arg[L])
{
arg = NULL;
}
uint bar[L] = {...};
foo(bar);
This is essentially the same as:
uint bar[L] = {...};
uint arg[L] = bar;
arg = NULL;
The pointer stored in bar
hasn't been affected by the assignment that happened inside the foo
function. If we did want to modify the pointer stored in bar
inside the foo
function, we should instead pass the address of bar
:
void foo(uint *arg[L])
{
*arg = NULL;
}
uint bar[L] = {...};
foo(&bar);
Which is equivalent to:
uint data[L] = {...};
uint *arg[L] = &bar;
*arg = NULL;
This time, arg
points to the memory that stores the data contained in bar
, which is the pointer to the array values. This means that if we modify the stuff that arg
points to, then we will also be modifying bar
.
Applying this to your code snippet would look like this:
void swap(uint *num_a[L], uint *num_b[L])
{
uint *tmp = *num_a;
*num_a = *num_b;
*num_b = tmp;
}
...
uint tmp_a[L] = {...};
uint tmp_b[L] = {...};
swap(&tmp_a, &tmp_b); // (tmp_a, tmp_b) <- (tmp_b, tmp_a)
Upvotes: 2