How Can I Add '\0' in char *msg = "Hello World"?

Mar 21, 2009 at 5:49am
1
2
3
4
char *here = "hello there whats up";
//&here[20] = '\0'; this does not work! 20 is the position after p
cout<<here<<" ****"<<endl;
cout<<&here[5]<<" **test**"<<endl;


1. How can i add a char '\0' after the letter p?
2. How can i add a termination char '\0' in the middle of the string?

This a sample example. Don't worry about the for loop, etc.

This is C++
Last edited on Mar 21, 2009 at 6:15am
Mar 21, 2009 at 7:15am
not possible, *here is a constant pointer and you cant change it.
it will fault.

if you want to do it, then explicitly allocate memory to it using malloc and then change the value.
Mar 21, 2009 at 7:37am
Why would you want to add '\0' after the last character?
It already has a '\0' after the last character.

PS.. The pointer isn't constant, it is the object (in this case the text string literal) that is constant (which is why you can't modify it).

Mar 21, 2009 at 8:09am
>>Why would you want to add '\0' after the last character?

I mainly asked to know how to place \0 in a middle a string. I think i have to use memmov()

>>The pointer isn't constant,

Right, its not constant...

>>it is the object (in this case the text string literal) that is constant (which is why you can't modify it).

1. Is string in C++ immutable?
2. I would agree with this statement that the text is object if the text stored in a variable declared as string, not char * since char does not have member functions you can call such as .size(), etc. Can you clarify your statement more please.
Mar 21, 2009 at 1:35pm
try with
1
2
char here[] = "hello there whats up";
here[11] = 0;


Here 'here' is an array so you can do whatever you want to its elements
Mar 22, 2009 at 2:53am
Yea, i know how to do that, but i'm ought to use the mentioned example. I got it anyway. Thansk
Mar 22, 2009 at 6:25am
when you declare and initialize the pointer same time the string is constant and hence you cant change the value. so this way you can take a pointe. either you have to take string as Bazzy said or else you have to allocate memory using malloc.
Topic archived. No new replies allowed.