简体   繁体   中英

Dynamically Allocating Memory to an array of Struct Nodes

I am trying to create an array of structs, with dynamically allocated memory,

Here's the struct definition I'm using:

struct node {
    int key;
    double probability;

    struct node *parent;
    struct node *children[255];
};  

Here is the declaration and initialization:

int base_nodes = sizeof(X)/sizeof(*X);
while ((base_nodes - 1)%(D-1) != 0){
    printf("Incrementing base\n");
    base_nodes++;
}

printf("base_nodes:\t%d\n", base_nodes);
struct node **nodes = malloc(base_nodes * sizeof(struct node));

if (nodes) {   
    printf("Size of nodes:\t%llu\n", sizeof(nodes));
} else { printf("Failed to allocate memory\n"); return 1;}  

Where X is another dynamically allocated Array of numbers defined before I call it here.
AFAIK, base_nodes is being calculated correctly, however the Size of nodes: is reporting 8, rather than 10. I have tried base_nodes less than 8 and it also returns 8.

Could someone explain why this happens? And how to do it properly?

The program I'm making is a D-ary Huffman code generator given a PMF.

I also attempted to realloc later on in the program and it seems to have had no effect:

nodes = realloc(nodes, ((sizeof(nodes) + 1) * sizeof(struct node)));
if (nodes) {
     printf("New size:\t%llu\n", sizeof(nodes));
} else { printf("Not enough memory\n"); }

You're trying to obtain the number of elements of type struct node , allocated dynamically, using the operator sizeof() on the pointer itself, which will just return the size of a pointer on your machine, which is 8 bytes as it seems to be a 64 bit machine. I think you're confused by the fact that when you allocate some memory statically in an array you can use sizeof() operator to return the number of elements allocated, ie

myType a[N];

number_of_elements = sizeof(a)/sizeof(myType)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM