[Solved] How to assign a struct to an array of pointers of the struct? [closed]


void A_output(struct msg message)
{
    struct pkt packet;

[...]

    packets[counter++] = (pkt*)&packet;

This last line assigns the address of a variable with automatic storage duration (a local variable) to an object with static storage duration (a global). Once your function exits, the variable with automatic storage duration doesn’t exist anymore, therefore the pointer doesn’t point to a valid location. Using this pointer later is undefined behavior, but it’s quite likely that your function reuses the same memory location for your struct pkt packet every time it is invoked, leading to the behavior you describe.

What you have to do is for example allocate memory for every element in packets with malloc() or new:

struct pkt *packet = malloc(sizeof *packet); // C style
// or:
pkt *packet = new pkt(); // C++ style

[...] // fill *packet

packets[counter++] = packet;

Don’t forget to free() (C) or delete (C++) all the packets when you’re done.

On a side note, in your original code, the cast (pkt*) is redundant. &packet already has the type struct pkt *. But as this is wrong anyways, it doesn’t matter much here.

solved How to assign a struct to an array of pointers of the struct? [closed]