1
struct {
    char* engine;
}car1,car2;

int main(void) {
    car1.engine = "engine a";
    car2.engine = "engine 2";
 
}

I'm learning thru a video on youtube about structs, and I tried running this code which was shown as an example. But VS would give me an error saying "a value of type 'const char*' cannot be assigned to an entity of type'char*'." I don't know why this happens. It would run flawlessly in the video. For one thing, my Vs is a cpp file. But isnt c code supposed to work in c++?

kimk463
  • 13
  • 3
  • 3
    C and C++ are different languages. That is not legal C++ code. – Retired Ninja Aug 24 '21 at 01:22
  • Does this answer your question? [Using char\* with strings in c++](https://stackoverflow.com/questions/64016111/using-char-with-strings-in-c) – Retired Ninja Aug 24 '21 at 01:24
  • You can just declare the member variable `const char* engine;` The pointer itself isn't const, only the chars it points to. – doug Aug 24 '21 at 01:45

1 Answers1

1

But isnt c code supposed to work in c++?

Indeed not. Although there is some overlap between them, C and C++ are separate languages. Some C programs aren't C++ programs and some C++ programs aren't C programs.

I don't know why this happens.

The error message explains the problem. String literals are arrays of const char, and such objects don't implicitly convert to char*. The conversion used to be allowed, but deprecated prior to C++11. Since then the conversion is no longer allowed and the program is ill-formed.

eerorika
  • 232,697
  • 12
  • 197
  • 326