Code:typedef char * Str; int main() { Str name = "joe name[1] = 'i'; cout << name << endl; return 0; }
Can someone explain to me why it doesn't output "jie"? It gives me a memory error.
Code:typedef char * Str; int main() { Str name = "joe name[1] = 'i'; cout << name << endl; return 0; }
Can someone explain to me why it doesn't output "jie"? It gives me a memory error.
Because the string "joe" is stored as read-only in the code segment. All literal strings are stored read-only.
There's a huge difference between:
andCode:char *string = "joe";
It's in the comp.lang.c FAQ:Code:char string[] = "joe";
http://www.eskimo.com/~scs/C-faq/q1.32.html
http://www.eskimo.com/~scs/C-faq/q16.6.html
Well..
1) Str is a pointer to a char, which you havent pointed to any memory or given its own memory to use.
2) Str name = "joe, you forgot to close the quotation and use the semi colon.
3) After using Str name = new char[10] (length of 10 chars for example), you will need to use strcpy (I believe) from .. <cstdlib> or one of those C #include files, that have functions to copy text to arrays.
You can still edit them 1 char at a time though without using that #include:
Not to suggest you should do this.. not really the most efficient thing to be doing, but if you wanted to do it the way you have in your topic post.Code:#include <iostream> using namespace std; typedef char* Str; int main() { Str name = new char[10]; name[1] = 'i'; cout << name << endl; cin.get(); return 0; }
Warning: Have doubt in anything I post.
GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101
How would I make it Str a new type?
typedef char[] Str;
Str name;
That doesn't work?
» Str is a pointer to a char, which you havent pointed to any memory or given its own memory to use.
that's a valid assignment. (with the exception of the missing quote and semi)
» You can still edit them 1 char at a time though without using that #include:
actually, this is how you would do it:Code:#include <iostream> typedef char* Str; //this is probably just a waste of your time. int main() { Str name = new char[10]; name[0]='i'; //if you assign one thing, it'll fill in the rest with '\0' name[1]='\0'; //you want to assign a null term, or you'll regret it std::cout << name << std::endl; delete[]name; //DO NOT FORGET to delete memory you allocate return 0; }
Last edited by major_small; 07-15-2005 at 03:34 AM. Reason: taipo
Join is in our Unofficial Cprog IRC channel
Server: irc.phoenixradio.org
Channel: #Tech
Team Cprog Folding@Home: Team #43476
Download it Here
Detailed Stats Here
More Detailed Stats
52 Members so far, are YOU a member?
Current team score: 1223226 (ranked 374 of 45152)
The CBoard team is doing better than 99.16% of the other teams
Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)
Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT