所以下面的代码用gcc编译时没有警告等,但是由于某种原因,交换代码实际上并没有通过交换值来修改数组…这里会发生什么?一个有趣的事情是temp
总是包含我想要的,它只是没有被使用。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//STRUCTURES
struct complex_
{
double re, im;
};
typedef struct complex_ complex;
//PROTOTYPES
int reverseBits(int x,int elements);
complex new_complex(double re, double im);
//MAIN
int main()
{
int n,m,elements = 8;
complex temp,**v;
//Allocate memory for the struct array...
v = malloc(sizeof(complex*));
*v = malloc(sizeof(complex)*elements);
//Initialize the struct array...
for (n = 0; n < elements; n++)
{
(*v)[n] = new_complex(n,0);
}
//View the initialized struct array contents...
for (n = 0; n < elements; n++){printf("%f+%fin", (*v)[n].re,(*v)[n].im);}
//Swap elements for the bit reversal...
for (n = 0; n < elements; n++)
{
m = reverseBits(n,elements);
temp = (*v)[n];
(*v)[n] = (*v)[m];
(*v)[m] = temp;
}
//View the new swapped struct array contents...
for (n = 0; n < elements; n++){printf("%f+%fin", (*v)[n].re,(*v)[n].im);}
return 0;
}
//FUNCTION DEFINITIONS
int reverseBits(int x,int elements)
{
//This function performs a binary bit reversal
//for example 3 = 011 => 110 = 6...
int num_bits = log2(elements);
int reverse_x = 0;
int i;
for (i = 0; i < num_bits; i++)
{
if((x & (1 << i)))
reverse_x |= 1 << ((num_bits - 1) - i);
}
return reverse_x;
}
complex new_complex(double re, double im)
{
//This function creates a new complex number.
complex r;
r.re = re;
r.im = im;
return r;
}
如果您将数组的所有项与"反向"索引处的项交换一次,那么您将再次以开始状态结束。ie。,对于大小为8的数组,执行以下交换:
- 将索引为0的项与索引为0的项交换
- 将索引为1的项与索引为4的项交换(a)
- 将索引为2的项与索引为2的项交换
- 将索引3处的物品与索引6处的物品交换(b)
- 将索引为4的物品与索引为1的物品交换(a)
- 将索引为5的项与索引为5的项交换
- 将索引6的物品与索引4的物品交换(b)
- 将索引为7的项与索引为7的项交换
请注意,标记为相同字母的交换((a)或(b))相互抵消,其他交换为无操作