Connecting Tech Pros Worldwide Forums | Help | Site Map

string troubles

Newbie
 
Join Date: Oct 2005
Posts: 1
#1: Oct 11 '05
Hi All -
is this allowed in c++? it gives an access violation in Microsoft Visual C++.

int main()
{
char* c = "Hello There!";
c[0] = 'J';

return 0;
}

is that because of windows or am i just writing bad code? just learning c++.

Thanks!

Newbie
 
Join Date: Dec 2006
Posts: 2
#2: Dec 6 '06

re: string troubles


The reason your codes doesn't work is that
you used a char pointer that points to data segment then you tried to change the datasegment ,which you are not allowed to at all!

LOOK:
char*cp="Hello,World!";

Now cp points to a string in the data segment,which the programmer doesn't have to change....
Ganon11's Avatar
Moderator
 
Join Date: Oct 2006
Location: New York, United States of America
Posts: 3,428
#3: Dec 6 '06

re: string troubles


Why not just use std::string instead of a pointer character array?
Member
 
Join Date: Nov 2006
Location: Antipolo, City
Posts: 55
#4: Dec 7 '06

re: string troubles


hi there,

actually like what gannon said you can used a simple string to this, and it may become more easy to read :
int main()
{
string MyString;
MyString = " Hello There";
cout << MyString <<end1;
return 0;
}

by this you can easily visuallized the output ok


regards,
Reply