2

I have a problem to assign a string literal to an array of chars. This is my code:

#include <iostream>

using namespace std;
struct CandyBar{
    char brand[20];
    double weight;
    int calories;
};
int main()
{
    char a[20] = "Mocha Munch";
    cout << a;
    CandyBar snack;
    snack.brand = "Mocha Munch";
    snack.weight = 2.3;
    snack.calories = 350;
    cout << "Brand of snack: " << snack.brand << endl;
    cout << "Weight of snack: " << snack.weight << endl;
    cout << "Calories of snack: " << snack.calories << endl;
    return 0;
}

My question is why with a[20] I can assign it to the array, but with brand I cannot.

1
  • "why with a[20] I can assign it to the array" You can't. Commented Sep 13, 2015 at 17:00

1 Answer 1

5
char a[20] = "Mocha Munch";

This is initialisation of character array a (not assignment). The language specifically allows initialising character arrays from string literals.

snack.brand = "Mocha Munch";

This is assignment into an array. The language does not allow assigning entire arrays (at all).

If you want to use a string in C++, don't waste time with cumbersome, error-prone character arrays. Use std::string.

Sign up to request clarification or add additional context in comments.

Comments

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.