0

So I'm calling heapsort on an array in C.

My heapsort function looks like this:

void heapSort(int keys[], int numKeys){
...
int tmp[numKeys];
for(int i=0; i<numKeys; i++){
    tmp[i] = maxVaue(h);
    deleteMax(h);
}

*keys = tmp;
}

What I'm trying to do is change keys to point to the new array, as the function return type is void. Is there any way to do this with pointers, or do I need to just memcpy the array?

Steven Morad
  • 2,511
  • 3
  • 19
  • 25
  • 1
    Arrays are not assignable, and you can't use `tmp` outside the function (it's out of scope when the function returns), so you need to use `memcpy()` anyways. –  Apr 30 '13 at 04:31
  • Alright, thanks. I just wanted to know if it was possible. – Steven Morad Apr 30 '13 at 04:34

3 Answers3

3

Arrays are not directly assignable, and also you can't use tmp outside the function, since it's out of scope when the function returns. You must use memcpy().

2

If you want to change what keys points to, you'll have to declare it as int **. And use explicit dynamic allocation (use of malloc) rather than a C99 Variable-Length array.

Medinoc
  • 6,577
  • 20
  • 42
1
void heapSort(int **keys, int numKeys){
    int tmp = malloc(sizeof(int)*numKeys);
    ...
    free(*keys);
    *keys = tmp;
}

int main(){
    int *keys = malloc(sizeof(int)*numKeys);
    ...
    heapSort(&keys, numKeys)
}    
shellfly
  • 892
  • 2
  • 13
  • 20