I am attempting to create an array of pointers to structs. I would like each of the structs to have the same values on initialization, but not the same pointers to them.
Currently I am attempting to do it like this:
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
struct Node {
float value;
bool evaluated;
struct Node* children[10];
};
void main() {
int i;
struct Node* node = &(struct Node) {
.value = 0,
.evaluated = false,
.children = { 0 }
};
for (i = 0; i < 10; i++) {
node->children[i] = &(struct Node) {
.value = 0,
.evaluated = false,
.children = { 0 }
};
printf("Index: %d, pointer: %p\n", i, node->children[i]);
}
}
Unfortunately, this gives me these results:
Index: 0, pointer: 00DEF640
Index: 1, pointer: 00DEF640
Index: 2, pointer: 00DEF640
Index: 3, pointer: 00DEF640
Index: 4, pointer: 00DEF640
Index: 5, pointer: 00DEF640
Index: 6, pointer: 00DEF640
Index: 7, pointer: 00DEF640
Index: 8, pointer: 00DEF640
Index: 9, pointer: 00DEF640
Is there any way I could produce this in such a way as to give the same results, but with different pointers to each of the structs?
mallocand friends?node->children[i]is the address of the pointer you just initialized to a non-NULL value.