C语言数组与指针(Arrays and Pointers)
A pointer to a given data type can store the address of any variable of that particular data type. For example, in the following code, the pointer variable pc
stores the address of the character variable c
.
char c = 'A';
char *pc = &c;
Here, c
is a scalar variable that can store only a single value.
However, you are already familiar with arrays that can hold multiple values of the same data type in a contiguously allocated memory block.
So, you might wonder, can we have pointers to arrays too? Indeed, we can.
Let us start with an example code and look at its output. We would discuss its behavior subsequently.
char vowels[] = {'A', 'E', 'I', 'O', 'U'};
char *pvowels = &vowels;
int i;
// Print the addresses
for (i = 0; i < 5; i++) {
printf("&vowels[%d]: %u, pvowels + %d: %u, vowels + %d: %u\n", i, &vowels[i], i, pvowels + i, i, vowels + i);
}
// Print the values
for (i = 0; i < 5; i++) {
printf("vowels[%d]: %c, *(pvowels + %d): %c, *(vowels + %d): %c\n", i, vowels[i], i, *(pvowels + i), i, *(vowels + i));
}
A typical output of the above code is shown below
&vowels[0]: 4287605531, pvowels + 0: 4287605531, vowels + 0: 4287605531
&vowels[1]: 4287605532, pvowels + 1: 4287605532, vowels + 1: 4287605532
&vowels[2]: 4287605533, pvowels + 2: 4287605533, vowels + 2: 4287605533
&vowels[3]: 4287605534, pvowels &#