Hi guys!
I'm new to this world, and I'm finding some problems on pointers (as most of people on the 1st time they encounter them).
I'm going to explain my problem step by step. First of all i try to define a new struct for complex numbers (maybe some already exist).
My code is:
Code:
typedef struct {
float real;
float img;
} complex;
Now I need to write a function that, when called, generates a vector of complex numbers.
These numbers must have img part =0 and real part = +1.0 or -1.0, in random way. So I thinked I could use rand() function to generate random int numbers. If generated int %2 ==0 then real part of my complex number is +1.0, in the other case -1.0.
Maybe there's a finer way to implement this, but it should work I think. After I filled my vector, I return a pointer to the 1st element of the vector.
My code:
Code:
#include "complesso.c"
#include <time.h>
#define LENGTH 1023
complex* randomarray(){
complex vettore[LENGTH];
complex *first;
int i, iseed;
iseed = time(NULL);
srand (iseed);
for (i=0; i<LENGTH; i++)
{
vettore[i].img=0.0;
if(rand()%2==0)
vettore[i].real=-1.0;
else
vettore[i].real=1.0;
}
first=&vettore[0];
return first;
}
At this point, my main function should get this pointer and print, for each element of the vector, real part and img part. It compiles but it sometimes gives strange values, like 0.0, or extremely big numbers, or img parts =/=0, so I tought there's some problem with pointers.
My code:
Code:
#include <stdio.h>#include "complesso.c"
int main(){
int i;
complex *first;
complex x;
first=randomarray();
for (i=0;i<1023;i++){
x= *(first+i);
printf("%d %1.1f %1.1f \n", i, x.real, x.img);
}
system("PAUSE");
}
Any suggestion will be appreciated