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 + 3: 4287605534, vowels + 3: 4287605534
&vowels[4]: 4287605535, pvowels + 4: 4287605535, vowels + 4: 4287605535
vowels[0]: A, *(pvowels + 0): A, *(vowels + 0): A
vowels[1]: E, *(pvowels

C语言中数组名是一个指向其首元素的常量指针,如a[i]等同于*(a+i)。当传递整个数组给函数时,默认传递的是指向首元素的指针,允许使用指针进行数组处理。混淆指针和索引会导致错误,正确做法是通过指针加减操作访问数组元素。
最低0.47元/天 解锁文章
165

被折叠的 条评论
为什么被折叠?



