C语言中指针操作主要有以下几种:
示例:
#include <stdio.h> int main(void) { int urn[5] = {100,200,300,400,500}; int *ptr1,*ptr2,*ptr3; ptr1 = urn; ptr2 = &urn[2]; printf("pointer value, dereferenced pointer, pointer address:\n"); printf("ptr1 = %u, *ptr1 = %d, &ptr1 = %u\n",ptr1,*ptr1,&ptr1); //指针加法 ptr3 = ptr1 + 4; printf("adding an int to a pointer:\n"); printf("ptr1 + 4 = %u,*(ptr1 + 4)=%d\n",ptr1+4,*(ptr1+4)); //指针自增 ptr1++; printf("values after ptr1++:\n"); printf("ptr1=%u,*ptr1=%d,&ptr1=%u\n",ptr1,*ptr1,&ptr1); //指针自减 ptr2--; printf("values after ptr2--:\n"); printf("ptr2=%u,*ptr2=%d,&ptr2=%u\n",ptr2,*ptr2,&ptr2); --ptr1; ++ptr2; printf("Pointers reset to original values:\n"); printf("ptr1=%u,ptr2=%u\n",ptr1,ptr2); //指针相减 printf("subtracting one pointer from another:\n"); printf("ptr2=%u,ptr1=%u,ptr2-ptr1=%u\n",ptr2,ptr1,ptr2-ptr1); //一个指针减去一个整数 printf("subtracting an int from a pointer:\n"); printf("ptr3=%u,ptr3-2=%u\n",ptr3,ptr3-2); }
程序运行结果如下图: