Search code examples
c++arrayspointersstructuredynamic-memory-allocation

How to access the members of a dynamic array of structures with pointers?


This is the main structure:

#include <iostream>
using namespace std;

struct CandyBar 
{
    char brand_name[30];
    float candy_weight;
    int candy_calories;
};

int main()
{
    CandyBar * snack = new CandyBar [3];

    return 0;
}

I managed to initialize the dynamically allocated 3 structures in an array of 3 elements. I tried to access the structures via:

snack[0]->brand_name = "Whatever";

with no result, even with the other method:

(*snack[0]).brand_name = "Whatever";

I really have no clue, since I have been studying these for a couple of days.


Solution

  • Since snack is an array of structures, just use snack[0].brand_name.

    You also can't copy a string just by using = in C. Use strcpy instead:

    strcpy(snack[0].brand_name, "Kitkat");