1

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.

1
  • Error: expression must be a modifiable lvalue Commented Sep 28, 2012 at 1:30

2 Answers 2

2

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");
Sign up to request clarification or add additional context in comments.

2 Comments

I discovered that assigning with = is illegal with membership operators, while legal in general i.e. char words[20] = { "Lots of words"}; Venturing into the esoteric corners of the language, thanks.
Actually, it's only legal when initializing char[] arrays (or when it is treated as char *).
0

In C++, strings are arrays, and arrays cannot be copied using =. Try:

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

3 Comments

Thanks for the input, I had completely ignored I could include <cstring>
Should be 'string literals are arrays'.
You both answered at the same time, so I've accepted nneonneo's final answer because he answered the very first time, sorry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.