指针
能解引用*(能代表它),被给了一个地址
空指针
没有写的权限
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
野指针
内存已被删除,没有写权限的内存,只能通过自身习惯避免
1、未初始化,随机(垃圾内存)
2、释放删除未置空堆(垃圾堆)
3、返回局部变量的地址(垃圾栈)
01 步长 p+1;&p+1;(char*)&p+1
p+1
指针步长(类型步长);
&p+1
指针地址步长;
(char*)&p+1
//按类型(char)加1(1*sizeof(char))//03 正确/错误的位置有说到
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void test1()
{
//指针的步长p+1
//指针找地址,类型取内存大小
char* p = NULL;
//类型步长
printf("%p\n", p);
printf("%p\n", p+1);
//地址步长
printf("%p\n", &p);
printf("%p\n", &p + 1);
}
void main() {
test1();
system("pause");
}
02 到where读写n*sizeof(类型)的内存
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void test2() {
char buf[100] = { 0 };
int a = 100;
memcpy(buf + 1, &a, sizeof(int));
printf("%p\n", buf);
printf("%p\n", buf+1);
//到buf+1*sizeof(char)的地址读取4字节的数据
printf("%d\n", *(buf + 1));
//
char* p=&buf;
//(int*)的作用,+1实际上是:+1*sizeof(int)
printf("%d\n", *(p + 1));
printf("%d\n\n", *(int*)(p + 1));
}
void main() {
test2();
system("pause");
}
03 指针步长——结构体中的成员变量
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stddef.h>
//3
typedef struct persons
{
char name[21] ;
int age;
}persons;
test3()
{
persons psn = { "毛修之" ,35};
int age;
// #include <stddef.h>
int sub = offsetof(persons, age);
//persons与age的内存距离,name对齐24
printf("%d\n",sub);
//
printf("%p\n", &psn);
//正确
printf("%p\n", (char*)&psn + sub);
printf("%d\n", *((char*)&psn + sub));
//错误,psn是persons类型,相当于+sub*sizeof(persons)
printf("%p\n", &psn + sub);
printf("%d\n", *(&psn + sub));
}
void main() {
test3();
system("pause");
}