交换/交换指针时未定义的行为

时间:2013-04-11 19:51:45

标签: c pointers

我创建了动态数组。填写是否具有特定值。打印它。但是在交换/交换指针之后(任务是在某些条件下交换行)

条件取决于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? */
      }
}

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

你可以尝试

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

答案 2 :(得分: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;