1.使用指针时,指针需指向程序内部已申请的空间。见例1与例2
2.指针偏移一个单位的大小取决于指针指向的类型。
3.在不知道指针所指向的位置时需要将指针等于NULL,则指针的地址为0x00000000。方便检测是否申请成功,因为指针的地址是从1开始
例1:程序未申请的空间,去读取
#include <stdio.h>
int main()
{
int a=10;//申请a四个字节的空间
int *p=&a;//申请int *p 四个字节的空间,p内存储为a的地址
int *pp=NULL;
printf("%d\n",*p);//通过*p打印a中的内容
printf("%d\n",*(p+1));//程序未申请p+1个空间的内容,无法去读,将会报错
如图1
return 0;
}
例2: 程序未申请的空间,去写入
#include <stdio.h>
int main()
{
int a=10;
int *p=&a;
(p+1)=100;//程序未申请的空间去写入
printf("%d\n",*p);
printf("%d\n",*(p+1));
return 0;
}
翻译为a变量附近的内容被破坏了。
#include <stdio.h>
int main()
{
int a=10;
int *p=&a;
char c='b';
char *ppp=&c;
double b=11;
double*pp=&b;
printf ("%d\n",p);
printf("%d\n",p+1);
printf("%d\n ",pp);
printf("%d\n",pp+1);
printf("%d\n",ppp);
printf("%d\n",ppp+1);
return 0;
}