#Pointer Array is Changing Values in Normal Array

5 messages · Page 1 of 1 (latest)

shadow wind
#

Hi, so I'm trying to only sort the pointer array in this code, but it's changing the values of the array its pointing at and I don't know why. Here is the parts of the code I find relevant:

The swap and sort function:
'''
void bubbleSort(int* listSort[])
{

for (int i = 0; i < SIZE; i++)
{
    for (int j = 0; j < SIZE - 1; j++)
    {
        if ((*listSort[j]) > (*listSort[j + 1]))
        {
            //int temp = list[j];

            //int* ptr = &listSort[0];

            //int* xptr = ptr + j; // temp

            //int* yptr = ptr + j + 1;

            swapIntPtr(&listSort[j], &listSort[j+1]);

        }

    }

}

}
//Call the swapIntPrt function from Bubble sort for swapping the
void swapIntPtr(int** xptr, int** yptr)
{

//int* zptr = *xptr;
 //*xptr = *yptr;

//*yptr = zptr;

int z = **xptr;
**xptr = **yptr;
**yptr = z;

}
'''

mossy mortarBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

wispy edge
#

Wrap your code:

mossy mortarBOT
#
How to Format Code on Discord
Markup

```cpp
int main() {}
```

Result
int main() {}
wide flume
#

You should do the formatting, but the answer is that int* listSort[] in a parameter is equivalent to int** listSort. Back in the day when C was invented and people had 3 bytes of RAM, it was unimaginable that you would ever want to pass an array by value. You always want to pass it by pointer to avoid that expensive copy, so C will silently fix this performance bug for you by turning the array into a pointer. C++ inherited that behavior.
Use std::array or std::vector instead for saner behavior.