yulian
yulian

Reputation: 1627

Undefined behaviour while swapping/exchanging pointers

I've created dynamic array. Filled if with certain values. Printing it. But after swapping/exchanging pointers (the task is to exchanging lines on certain conditions)

Conditions depend on sumL. I'm not describing detailes in order not to waste your time.

The problem is in exchanging pointers.

for ( k = 0; k < N - 1; k++ )
{
    for ( i = 0; i < N - 1; i++
       if (sumL[i] > sumL[i+1])
       {
           temp = sumL[i];            // works
           sumL[i] = sumL[i+1];
           sumL[i+1] = temp;

           temp = *a[i];              // doesn't work. Array is not the same: elements 
           a[i] = a[i+1];             // contain other values.
           *a[i+1] = temp;            /* What is wrong? */
      }
}

Upvotes: 0

Views: 73

Answers (3)

Caladan
Caladan

Reputation: 1491

temp = *a[i];              //temp == value pointed by a[i], NOT pointer
a[i] = a[i+1];             // here you actually copy the pointer 
*a[i+1] = temp;            // here you again write value, NOT pointer

You should do:

type* temp_ptr = a[i];     
a[i] = a[i+1];
a[i+i] = temp_ptr;

Upvotes: 1

Bryan Olivier
Bryan Olivier

Reputation: 5307

If you want to swap pointers, then it should probably read

temp = a[i]; a[i] = a[i+1]; a[i+1] = temp;

If you want to swap values, then it should probably read

temp = *a[i]; *a[i] = *a[i+1]; *a[i+1] = temp;

Upvotes: 2

Fabien
Fabien

Reputation: 13406

You could try

*a[i] = *a[i+1];

Upvotes: 1

Related Questions