Susan Susan - 1 month ago 7
C Question

Filling a tree using random values using loop

I have the following question:

I created this structure:

typedef struct Tree{
float pnt[2];
struct Tree *left;
struct Tree *right;
}Node;


My goal is to establish the initial tree with random points (each point of dim=2). We can do that manually from the main function something like this:

Node n[] = {
{{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}
};


However, I want to do that using a loop that fills each node with random point. Is it correct to do the following:

Node n;
int num_nodes = 6;

srand(time(NULL));
for (i = 0; i < num_nodes; ++i) {
n->pnt = (float) rand() / (float) RAND_MAX;
}

Answer

Not quite - since node is an array, and pnt is an array of two points within each struct, you would need to do something like this:

const int num_nodes = 6;
Node n[num_nodes];

srand(time(NULL));
for (i = 0; i < num_nodes; ++i) {
    n[i].pnt[0] = (float) rand() / (float) RAND_MAX;
    n[i].pnt[1] = (float) rand() / (float) RAND_MAX;
}