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 tempalways 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;
}
complex*, and then allocating an array ofcomplex, which the first pointer points to. You'd better just allocate an array ofcomplex*pointers -malloc(sizeof(complex*)*elements), and fill it usingnew_complex. Also, you shouldfreeall the allocated memory - first the complexes, and then the array.&vto it, and there do*v = some_other_complex_star_star. But if you'd like to change the array's content, you can pass it as is -v.