How does this function work

Hello all, how does this function work? especially in the second {} Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
 int *sortAsc(int *p, int n)
{
	int i, j;
	for (i = 0; i<n; i++)
		for (j = i + 1; j<n; j++)
			if (*(p + j)<*(p + i))
			{
				int temp = *(p + j);
				*(p + j) = *(p + i);
				*(p + i) = temp;
			}
	return p;
}
Perhaps it would be less confusing if you used subscript notation instead of using addition on the pointer. Also, better variable names would help. See if this code makes more sense:
1
2
3
4
5
6
7
8
9
10
11
12
13
int *sortAsc(int *theArray, int theArraySize)
{
    int i, j;
    for (i = 0; i<theArraySize; i++)
        for (j = i + 1; j<theArraySize; j++)
            if (theArray[j]<theArray[i])
            {
                int temp = theArray[j];
                theArray[j] = theArray[i];
                theArray[i] = temp;
            }
    return theArray;
}

I'm not sure why your function would return a pointer to the same array passed in as a parameter. Maybe you're supposed to return a sorted copy of the array?

In any case, the part between the most nested curly braces is swapping the two numbers if they're not in ascending order.
1
2
3
4
5
6
7
//if the number in the "j"th position is smaller than the one in the "i"th position...
if (theArray[j]<theArray[i])
{
    int temp = theArray[j]; //create a new variable to hold the original "j"th value
    theArray[j] = theArray[i]; //write over the original "j"th value with the "i"th value
    theArray[i] = temp; //write over the original "i"th value with our copy of the original "j"th value
}
Last edited on
The variable p is a pointer to the first element of the array of size n. Adding an int to a pointer will increment the address it holds by the product of the int and the data type's size. Each time 1 is added to the pointer, 4 (for ints on most systems) is added to the address.

It is a feature of C-style arrays (and later of std::vector) that its memory allocation is contiguous - thus the pointer shifts to the next cell of the array and then it is de-referenced it with the * operator - this is also known as the shift and dereference paradigm.

So this line of code:
if (*(p + j)<*(p + i)) effectively means if the value of the array in cell [0+j] is less than the value of the array in cell [0+i] ... do something etc
Thank you guys for the explanations.

theArray[i] = temp; //write over the original "i"th value with our copy of the original "j"th value

why does this i th value has to be write over?
Topic archived. No new replies allowed.