The main difference between using pointers and arrays in C language is that using a pointer array in C Language
In C, pointers and array names both represent addresses, but the two are very different. For Beginners, you must find out the differences between them.
First, let me give a simple example:
Char * p1 = "hello! "; // Defines the struct pointer p1, and points the pointer p1 to the string" hello !" .
Char s [10] = "hello! "; // Defines the array s and assigns its initialization value.
However, if char s [10]; s = "hello! "; In this case, an error is reported. Why? The reason is simple, because the array name is a constant.
Now, let me give two simple examples:
Example 1
Void main ()
{
Char p [] = "abcdef ";
P [0] = 'y ';
Printf ("% s", p );
}
Output Ybcdef in this program
Example 2
Void main ()
{
Char * p = "abcdef ";
P [0] = 'y ';
Printf ("% s", p );
}
This program throws an exception. Why?
In Example 2, char * p = "abcdef", the pointer p is stored in the stack area, but the string is a constant, stored in the constant area, the pointer p points to the first address of the string stored in the constant area. At this time, the value of the string in the constant area cannot be changed.
In example 1, char p [] = "abcdef" is used to copy the string "abcdef" in the constant area to the space of the array p in the stack area. Array p opens up space in the stack area. In this case, the value of the string can be modified because the value of the string in the stack area is modified. In addition, array name p is the first address of "abcdef" in the stack area.