Home > Mobile >  Array of integer pointers
Array of integer pointers

Time:10-04

I am trying to implement quick sort and trying to manipulate the array that has to be sorted, but the ff is giving me a totally different behavior so was wondering how different they could be. Say I have a base integer pointer (the array that has to be sorted):

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int *base_array;
int left;
int right;

//So how does the ff differ?
swap(base_array[left], base_array[right])
//swap(base_array   left, base_array   right)

The first swap is giving me a weird output while the second does seem to do well but I don't really know how different they are?

CodePudding user response:

You are not matching the swap function prototype since you are passing int instead of int *:

swap(&base_array[left], &base_array[right])
swap(base_array   left, base_array   right)

If you are using GCC then you can catch this kind of mistake by enabling the -Wall compiler flag. And even better, enabling this flag -Werror will treat all warnings as errors... This last one is a bit severe, but ensures quality :)

CodePudding user response:

The first call swap(base_array[left], base_array[right]) passes int values to swap which expects int pointers. The behavior is undefined, quite possibly a program termination. The weird output is a compiler warning: do not ignore these, they always indicate some kind of problem in the code that should be addressed.

The second call swap(base_array left, base_array right) is OK: it passes pointers and is equivalent to:

    swap(&base_array[left], &base_array[right])

Note the difference between base_array[left] which evaluates to the array element at index left and &base_array[left] which evaluates to the address of this element, ie: a pointer to it.

By the way, the question title is misleading: base_array is not an array of integer pointers, it is an array of int, the swap() function receives pointers to two array elements.

CodePudding user response:

In this function call

swap(base_array   left, base_array   right);

you re passing elements of the array by reference through pointers to them. So the function works correctly. It indeed expects pointers to the elements of the array that must be swapped.

This function call

swap(base_array[left], base_array[right])

is equivalent to the following

swap( *(base_array   left ), *( base_array   right ) );

That is you are not passing elements of the array by reference through a pointers to them by are passing the elements themselves of the type int. It means that the function will have undefined behavior because it will consider values of the elements as addresses

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}
  • Related