Char * to string

Hello.Does a char* needs to be const if I want to do char* c="Hello",or it can just stay like this.In my exercise I need to make some variables that are only char* but I must give them names later in the exercise.
For example
1
2
3
4
5
6
class T
{
  char *c;
T();//is it possible to somehow to give c some name 

};
If you want a pointer to a string literal, it has to be a pointer to a const char, i.e. const char*. It is dangerous to modify the memory where string literals are stored, so you should never point to that memory , so you should never use a pointer to a non-const to access it.

I suspect what you want to do is have c be a pointer to some C-string either on the stack, or the heap, that you can modify. In that case, you need to set it to point at some memory you've assigned to that string, rather than to point to a string literal.

Do you understand the difference between a pointer to a char, and a C-style string?

Do you understand the difference between a string literal, and a C-style string variable?

Last edited on
I don't know am i wrong but i think that char * points to the firs element of some array of characters .I also think that const char* is equal to string and that is also equal array of characters.
char * is a C thing. Its better to not use it at all in c++ unless unavoidable (due to mixed language programming mostly).

a c-string is indeed a pointer to the first letter of a zero terminated block of characters.
const char * may be the same thing except as a constant, you cannot modify it. (you can also have a char * or const char * that is just raw bytes, not a c style string -- and accidental use of this as a c-string will cause problems!).

honestly I find arrays to be safer for C strings, but if you must do a char *, do this:
char * s = new char[max];
strcpy(s, "Hello");

then you can modify it later. It isnt a constant, you just assigned a value.

I cannot stress enough how nice arrays are for this stuff, though.


char s[100] = "Hello";
strcat(s, " World!");

using c++, though:

1
2
3
4
5
6
7
class T
{
 string c;
T() {c = "sure it is";}//is it possible to somehow to give c some name 
T(string in) {c = in;}//or that
};


to do the above using C strings via a char *, its a big mess, you need to new up some memory and destroy that in your destructor (missing) and use a strcpy to set the value in the constructor.
Last edited on
Thank you very much for your help.
Topic archived. No new replies allowed.