0

Every reference I can find suggests I can use char* cName = "Some Text", but my VS2019 complains.

I have seen many examples here on Stackoverflow using that syntax and many youtube videos also demonstrating its use.

Can anyone explain why I am seeing my error (See image below)

Example of issue

cgts
  • 54
  • 3
  • _Every reference I can find suggests I can use `char* cName = "Some Text"`_. Really? Which ones? Maybe, you should better learn from some [good C++ books](https://stackoverflow.com/q/388242/580083). – Daniel Langr May 18 '20 at 10:27
  • 1
    It was possible in older versions of C++, but it has been deprecated now. Your reference material is most likely out of date if it says that it is valid. – dreamlax May 18 '20 at 10:27
  • 1
    fwiw youtube videos arent the most reliable source and even Stackoverflow answers should not be trusted blindly. Also consider that C++ is evolving, so what is ok now may be not ok with the next standard – 463035818_is_not_an_ai May 18 '20 at 10:33
  • @dreamlax -- it's not just deprecated; it's gone. Deprecated means that it's okay, but might not be in future versions of the standard. – Pete Becker May 18 '20 at 13:03
  • @PeteBecker yeah it was a poor choice of words, I remember thinking the phrase "it was deprecated a while ago now" but obviously my hands typed something else! – dreamlax May 18 '20 at 13:08
  • "Every reference I can find suggests..." Oh my, you need to find better quality references. – Eljay May 18 '20 at 13:21
  • It was only allowed for compatibility with *old* C code. Writing to that `char *` would crash your program even going back to 1994 on a HPUX. Character literals get put into the read-only text segment of a program. – Zan Lynx May 18 '20 at 17:09

2 Answers2

5

You can't do it since C++11. The type of c-style string literal is const char[] (array of const char), and could decay to const char* (pointer to const char) but not char* (pointer to non-const char).

In C, string literals are of type char[], and can be assigned directly to a (non-const) char*. C++03 allowed it as well (but deprecated it, as literals are const in C++). C++11 no longer allows such assignments without a cast.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
0

Since char* is a pointer to char,the typical way to do this is to allocate a memory and than point the pointer to the memory you created.

for example: in C and C++ you can use

char* example = (char *)malloc(sizeof(char) * 5); //#include<stdlib.h> required
strcpy(example, "CGTS"); // #include<string.h> required

free(example); //call this after all usage of example 

In C++, you can used new instead of malloc, and you can also take a look at std::string in C++, it might be useful for you.

Jim Pp
  • 147
  • 4