Reputation: 1373
So the following code compiles with no warnings etc with gcc, but for some reason, the swap code doesn't actually modify the array by swapping the values...What could be going on here? One interesting thing is that temp
always contains what I want, it just doesn't get used.
#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;
}
Upvotes: 1
Views: 1574
Reputation: 16243
If you swap all items of the array once with the item at the "reversed" index, then you'll end up with the start state again. ie., for an array size of 8, these swaps are done :
Notice that the swaps marked with the same letter ((a) or (b)) cancel each other out, and the others are no-ops.
Upvotes: 3