Arrow Membership Operator

The line pfish->kind = "guppy" produces an error statement: "invalid array assignment." Why does this happen when I'm assigning the address of the first char element ('g') to the array of chars in the structure pointed to by pfish?

1
2
3
4
5
6
7
8
9
  struct fish 
    {
        char kind[6];
        int weight;
        double length;
    };
    fish* pfish = new fish;
    pfish->kind = "guppy";
    cout << pfish->kind <<"\n";
You cannot assign to a character array. I recommend using std::string instead, but if you can't, use strcpy or use a character pointer instead of a character array.

Since you named it "kind", I may also suggest looking into OOP and Polymorphism, or else using an enum instead of a string.
Last edited on
How is it different from:

char kind[6] = "guppy";

(which works fine)?
char kind[6] = "guppy"; is an initialization.
1
2
char kind[6];
kind = "guppy";
This is an assignment after initialization.

The fact that you can use = for initialization is a quirk of the language - it does not have the same meaning as assignment.
Last edited on
Topic archived. No new replies allowed.