c++arrayscchardereference

storing char in char array - incompatible types in assignment of char to char[]


I have a struct with a char array member as such:

typedef struct {
    // ...
    char myCharArr[200];
} myStruct;

I have a dynamic array of these structs. When I try to store a character in myCharArray it shows an error message of incompatible types in assignment of 'char' to 'char[200]'

int num = 2;
myStruct* data = new myStruct[num];

// ...

data[i].myCharArr = 'a';  // error here

But if I use the line below, it works fine

*data[i].myCharArr = 'a';

I am getting back into C++ after some time so would really appreciate if anyone could explain the difference between the two. From what I understand and remember, I can use strcpy and other variants to store a write a string into a chararray, but it is a single char in this case. Why does dereferencing the array work to store the char into chararray? Additionally, how does the null terminator come into this?


Solution

  • If anyone could explain the difference between the two.

    data[i].myCharArr gives us the data member myCharArr which is of array type char[200] and you're trying to assing a character literal 'a' to it which is not possible. Note that c-style arrays also decay to pointer(here char*).


    On the other hand, when you apply operator* to *data[i].myCharArr, it is equivalent to writing:

    *(data[i].myCharArr)    //same as data[i].myCharArr;
    

    due to operator precedence.

    This time, we still get a char[200] from data[i].myCharArr but it decays to a char pointer. The operator* then derefences that pointer and gives us a char which can be assigned 'a'.


    Note that in modern c++, you can use std::string, std::array, std::vector etc. Also, you can directly name the class instead of using typedef.