This article is from the "high-quality C, C + + Programming Guide," through the reading and summary, and with examples to prove.
Array: Created on a static store or on a stack. The array name corresponds to a piece of memory whose address and capacity remain constant throughout the life cycle, and only the contents of the array can be changed.
Pointer: points to any type of block of memory at any point, characterized by "mutable", so pointers can be used to manipulate dynamic memory.
1. The size of arrays and pointers.
Char str[] = "Hello";
char* pStr = "Hello";
int* pInt = nullptr;
printf ("str len =%d\n", sizeof (str));
printf ("PStr len =%d\n", sizeof (PSTR));
printf ("PInt len =%d\n", sizeof (PINT));
Results:
STR has a length of 6 because the contents are "hello\0" and there is a '% ' terminator.
Although Pstr and pint are different types of pointers, they are all 4. So the length of the array depends on the content, and the length of the pointer is fixed at 4.
2, the contents of the array and pointers to the content of the same, but the contents of the storage address is not the same.
Char str[] = "Hello";
printf ("str address =%d\n", str);
char* pStr = "Hello";
printf ("PStr address =%d\n", pStr);
char* pStr2 = "Hello";
printf ("PStr2 address =%d\n", PSTR2);
Results:
As can be seen, although the content of STR and pstr point to the same content, but the content of the address is not the same.
The Hello that Str holds is on the stack, the array opens up the memory space to hold, so can modify the content, if str[0]= ' X ', so the output of STR is Xello.
The pointer is pointing to memory, and "Hello" is now stored in the static storage area. where pstr and PSTR2 output the same address. Because "Hello" is in the static store and cannot be modified, pstr[0]= ' x ' causes a run-time error.
3. It says that you cannot modify the pointing content by pstr[0], because "Hello" is a string constant. But if pstr points to an array, it is possible to modify the contents of the array by pointers.
Char str[] = "Hello";
char* pStr = str;
Str[0] = ' a ';
printf ("str =%s\n", str);
printf ("pStr =%s\n", pStr);
Pstr[0] = ' B ';
printf ("str =%s\n", str);
printf ("pStr =%s\n", pStr);
*pstr = ' C ';
printf ("str =%s\n", str);
printf ("pStr =%s\n", pStr);
Results:
You can see that the array contents are changed by pstr[0] and *pstr.
4, the array corresponds to a piece of memory area, the pointer is a piece of memory area. So the array is not able to point to the next element by self-addition, and the pointer can.
An error occurs when an element is removed with an array name using self-addition (++STR), and the pointer is removed from an element (++PSTR).
Pointers and arrays-high-quality C, C + + Programming Guide