Comparison of usage differences between char * and char [] in C Language
This article analyzes the differences between char * and char [] in C. Share it with you for your reference. The specific analysis is as follows:
In general, many people will 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 (www.jb51.net); // 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
# Includeint 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
I believe this article provides some reference for you to learn C language programming.