It is still very hard to pick up the lost items. Today I found that I don't even know the difference between char * and char.
Many people think that these two definitions have the same effect, but they are actually quite different. Some of my personal opinions are as follows. I hope to correct them if they are incorrect.
Essentially, char * s defines a char pointer. It only knows the memory unit to which it points, and does not know the size of the memory unit. Therefore:
When char * s = "hello";, the value cannot be assigned using the s [0] = 'a'; statement. This will prompt that the memory cannot be "written ".
After char s [] = "hello"; is used, values can be assigned using s [0] = 'a';, which is a regular array operation.
If char s [] = "hello ";
Char * p = s;
You can also use p [0] = 'a'; because this is p = s, all pointer to the array.
The following is another definition:
Char * s = (char *) malloc (n); // where n is the size of the space to be opened
This sentence is actually equivalent:
Char s [n]; defines a pointer to an array to perform subscript operations on the array.
Example
The code is as follows: |
Copy code |
# Include <stdio. h> Int main (int argc, char * argv []) { Char * buf1 = "this is a test "; Char buf2 [] = "this is a test "; Printf ("size of buf1: % d \ n", sizeof (buf1 )); Printf ("size of buf2: % d \ n", sizeof (buf2 )); Return 0; } The result is: $>./Main Size of buf1: 4 Size of buf2: 15 |