研究下指针p+1之后,话不多说贴代码测试
#include<stdio.h>
struct test {
int a;
int b;
char c;
float d;
};
int main(void)
{
int *pint;
char *pchar;
struct test *pstruct;
printf("int size = %d, char size = %d, struct test size = %d\n", sizeof(int), sizeof(char), sizeof(struct test));
printf("pint = %d, pint + 1 = %d\n", pint ,pint + 1);
printf("pchar = %d, pchar + 1 = %d\n", pchar ,pchar + 1);
printf("pstruct = %d, pstruct + 1 = %d\n", pstruct ,pstruct + 1);
return 0;
}
int size = 4, char size = 1, struct test size = 16
pint = 0, pint + 1 = 4
pchar = 120231760, pchar + 1 = 120231761
pstruct = 4195392, pstruct + 1 = 4195408
代码中打印了char,int,以及test结构体的sizeof大小,然后打印出指针地址(不要在意指针地址是多少)
可以看出指针p和指针p+1的地址相差为这个指针类型的size,而不是地址+1。虽然这个结论我早就知道了,今天测试了下,结果是这样的。
可以得出结论指针+1所增加的地址值为这个指针类型所占用的内存大小的值。
联想到数组,结构体数组来讲,当前指针加一,正好指向下一结构体的地址,突然发现c语言的设计很富有哲学性。