Array Versus Pointer

What is the difference, then between an array and a pointer form? The array form (m3[]) cause an array of N elements (one for each character plus one for the terminating '\0') to be allocated in the computer memory. Each element is initialized to the corresponding character. Typically, what happends is that the quoted string is stored in a data segment that is part of the executable file; when the program is loaded into memory, so is that string. The quoted string is said to be in static memory. But the memory for the array is allocated only after the program begins running. At that time, the quoted string is copied into the array. Hereafter, the compiler will recognize the name m3 as a synonym for the address of the first array element, &m3[0]. One important point here is that in the array form, m3 is an address constant. You can't change m3, because that would mean changing the location (address) where the array is stored. You can use operations such as m3+1 to identify the next element in an array, but ++m3 is not allowed. The increment operator can be used only with the name of variables, not with constants.

The pointer form (*m3) also cause N elements in static storage to be set aside for the string. In addition, once the program begins execution, it sets aside one more storage location for the pointer variable m3 and stores the address of the string in the pointer variable. This variable initially points to the first character of the string, but the value can be changed. Therefore, you can can use the increment operator. For instance, ++m3 would point to the second character (E). 

In short, initializing the array copies a string from static storage to the array, whereas initializing the pointer merely copies the address of the string.


Array and Pointer Differences

Let's examine the differences between initializing a character array to hold a string and initializing a pointer to point to a string. (By "pointing to a string," we really mean pointing to the first character of the string.) For example, consider these two declarations:

char heart[] = "I love Tillie!";
char *head = "I love Millie!";

The chief difference is that the array name heart is a constant.

const char * p1 = "Klingon"; // recommended usage


你可能感兴趣的:(Array Versus Pointer)