Swap the pointers of two arrays in a function [duplicate]

混江龙づ霸主 提交于 2019-12-08 04:00:26

问题


I'm writing a mergesort without the copy part into an extra temp array. For this reason, I create an auxiliary array aux

int * aux
aux = (int *) calloc(n, sizeof(int));

where n is the size of the array. In the function merge, I want to swap both arrays at the end by using their pointer to continue with my algorithm. But if I swap the pointers, and print them to console, I got weird stuff:

Within the method itself, the pointers are swapped. But if I check after my method, back in my main, the pointers aren't swapped anymore. The call of my merge method:

merge(a, lo, mid, hi, aux);

where a is my main array, aux the auxiliary and lo, mid and hi are integers.

prototype:

void merge(int *a, int lo, int mid, int hi, int *aux);

I tried to swap them like this:

int temp;
temp = a;
a = aux;
aux = temp;

Can you help me solve this problem?

Thanks in advance!


回答1:


The error occurs because the pointers are passed by value.

Change them to pointers to pointers:

void merge(int **a, int lo, int mid, int hi, int **aux);

Swap like this:

int *temp;
temp = *a;
*a = *aux;
*aux = temp;

merge should then be called like this:

merge(&a, lo, mid, hi, &aux);



回答2:


I can spot 2 different problems with your approach:

1) Why are you using an int temporary variable to exchange int* pointers? This may cause issues if sizeof(int) != sizeof(int*), for example 64 bits systems. Why not using an int* temporary?

2) your a pointer in:

void merge(int *a, int lo, int mid, int hi, int *aux);

is passed by value, which means whatever changes you do on the pointer's value in your function will not be visible outside of it. You should rather use one of these approaches:

void merge(int **a, int lo, int mid, int hi, int *aux);

or:

void merge(int *& a, int lo, int mid, int hi, int *aux);

if you're in the c++ world.

Another thing: Passing the aux to the merge function may be somewhat redundant since you can very well allocate and deallocate it inside.



来源:https://stackoverflow.com/questions/23909134/swap-the-pointers-of-two-arrays-in-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!