0

我创建了动态数组。如果用某些值填充。打印它。但是在交换/交换指针之后(任务是在某些条件下交换行)

条件取决于sumL。为了不浪费你的时间,我没有描述细节。

问题在于交换指针。

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? */
      }
}
4

3 回答 3

2

如果你想交换指针,那么它可能应该读

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

如果你想交换值,那么它可能应该读

temp = *a[i]; *a[i] = *a[i+1]; *a[i+1] = temp;
于 2013-04-11T19:55:39.040 回答
1

你可以试试

*a[i] = *a[i+1];
于 2013-04-11T19:54:44.020 回答
1
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

你应该做:

type* temp_ptr = a[i];     
a[i] = a[i+1];
a[i+i] = temp_ptr;
于 2013-04-11T19:57:36.250 回答