所以下面的代码用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+%fi\n", (*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+%fi\n", (*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;
}
答案 0 :(得分:3)
如果您将数组的所有项目与“反向”索引处的项目交换一次,那么您将再次以开始状态结束。即,对于数组大小为8,这些交换完成:
请注意,标有相同字母((a)或(b))的掉期互相取消,其他则为无操作。