There is a good article about C String, basically, there are two ways of declaring a string, either statically or dynamically.
- To declared a string statically, we can either declare an explicit number of string length or not.
1: char label1[]="I am a test!";
2: char label2[100]="I am a test!";
The length of the first string is decided by the actual string length, while the second string is explicitly declared as having the length of 100. Both of ways declare a mutable string, which is different with char* label3="I am a test!". The later one are essentially the same with const char* label3="I am a test!" . If you try to do something like lable3[0]='i', you will encounter an access violation error.
Here is a good link about this problem: Basically, when you declare char* label3="I am a test!". it will be a constant string in the data section, this string constant has always the same address and is constant. You should always consider const char* label3="I am a test!" because the former is only for backward purpose.
2. To declare a string dynamically, the string length has to be passed in like this char* dynamicalString=new string[length+1]. The last character is reserved for '\0', the end of string. The string length (strlen) is length, not length+1.
No comments:
Post a Comment