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.
Printable View
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;
}
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;
}