计算机二级C语言考试数组,指针

img


计算机二级C语言考试这里的意思是p2-p1得出来的是偏移量?对指针很不了解,

指针相减就是求出他们之间相差多少个元素的位置,p1=a也就是p1指向a的第0个元素,p2指向a的第5个元素,所以5-0=5

Pointer Arithmetic
Additive operations involving a pointer and an integer give meaningful results only if the pointer operand addresses an array member and the integer value produces an offset within the bounds of the same array. When the integer value is converted to an address offset, the compiler assumes that only memory positions of the same size lie between the original address and the address plus the offset.

This assumption is valid for array members. By definition, an array is a series of values of the same type; its elements reside in contiguous memory locations. However, storage for any types except array elements is not guaranteed to be filled by the same type of identifiers. That is, blanks can appear between memory positions, even positions of the same type. Therefore, the results of adding to or subtracting from the addresses of any values but array elements are undefined.

Similarly, when two pointer values are subtracted, the conversion assumes that only values of the same type, with no blanks, lie between the addresses given by the operands.

指针运算
仅当指针操作数寻址数组成员且整数值在同一数组的边界内产生偏移量时,涉及指针和整数的加法运算才会给出有意义的结果。当整数值转换为地址偏移量时,编译器假定只有大小相同的内存位置位于原始地址和地址加上偏移量之间。
此假设对数组成员有效。根据定义,数组是一系列相同类型的值;其元素位于连续的内存位置。但是,除了数组元素之外的任何类型的存储都不能保证由相同类型的标识符填充。也就是说,空白可以出现在内存位置之间,甚至是相同类型的位置。因此,除了数组元素之外的任何值的地址相加或相减的结果都是未定义的。
类似地,当减去两个指针值时,转换假定只有相同类型的值(没有空格)位于操作数给定的地址之间。

如果两个指针向同一个数组,它们就可以相减,其为结果为两个指针之间的元素数目。

a数组名表示第一个元素的地址,也相当于&a[0];
而&a[5]就是第六个元素的地址,就是&a[5];

简单一点理解相当于下面这样
1 2 3 4 5 6
p2-p1=6-1=5

我对指针的理解是,指针就是存储了地址的变量,比如你int类型的指针,就是存储了int类型变量对应的一个地址。
而这里处理指针的概念,还有一个数组的概念,数组其实就是连续内存,然后按类型依次取,直接数组名就是首地址,而取一个变量的地址(用&)就是取对应变量的地址,这里a[5]对应的就是数组的首地址往后第五个下标,然后指针的计算,又是按照类型长度加的,比如,你可以用指针访问数组元素:

img


同时 你可以看看我的主页里回答过别人的指针相关,以前回答比较认真以及回答过不少,可以参考理解

p1=a 指p数组的第零个元素(即p[0])。
p2=&a[5] 指p数组的第五个元素(即p[5])。
p1-p2的值指元素的位置相差,即5-0=5;

供参考:

#include <stdio.h>
int main()
{
    int *p1,*p2,a[10];
    p1 = a;
    p2 = &a[5];
    printf("&a=%p, p1=%p, p2=%p, p2-p1=%d",a,p1,p2,p2-p1);

    return 0;
}

//&a=0019FF18, p1=0019FF18, p2=0019FF2C, p2-p1=5

我只能理解到 数组的第四个元素-数组的第一个元素。