指针概念:指针是一个变量,其值为另一个变量的地址,即,内存位置的直接地址。就像其他变量或常量一样
1:指针常量和常量指针
int a;
int *const p1=&a;//指针常量
const int *p2=&a;//常量指针
const 用来定义常量的;
2:指针数组和数组指针
int *p[N],p代表一个可存放N个整型指针类型元素的一维数组,p是指针数组。本质是数组,是常量。
int (*p)[N],p代表一个指向由N个整型数据组成的一维数组的指针。p是数组指针,本质是指针,是变量。
3:指针函数 与 函数指针
int * f(int x),f代表一个返回值为整型指针的函数。f是指针函数。本质是函数。
int (*f)(int x),f代表一个指向函数的指针,该函数的參数和返回值均为整型,f是函数指针,本质是指针。
4:简单的指针运算实例
定义一个整形数组,通过指针运算输出数组元素
#include<stdio.h>
int main()
{
int a[5]={1,25,6,8,7};
int *p,i;//*p是定义整形的指针变量
p=a;//将a数组的首地址给p
for( i=0;i<5;i++)
{
printf("%p\n",a);//输出这五个元素的地址
printf("%d\n",*p);
p++;//指针的递增
}
return 0;
}
结果
5:双重指针
#include<stdio.h>
int main()
{
int a=10;
int *p;
int **q;
p=&a;
q=&p;
printf("a的地址=%p\n",a);
printf("a的值=%d\n",a);
printf("a的地址%d\n",&a);
printf("%d\n",p);//a的地址
printf("%d\n",&p);//p的地址
printf("%d\n",*p);//p所储存a的值
printf("%d\n",**q);//a的值
return 0;
}
结果
6:传递指针给函数
#include<stdio.h>
#include<time.h>
void getSeconds(unsigned long *par);
int main ()
{
unsigned long sec;
getSeconds( &sec );
/* 输出实际值 */
printf("Number of seconds: %ld\n", sec );
return 0;
}
void getSeconds(unsigned long *par)
{
/* 获取当前的秒数 */
*par = time( NULL );
return;
}
调试结果
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,