C语言数组与指针(Arrays and Pointers)关系解析-差不多是一回事儿

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 &#
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值