02 06 指针基本概念(理论) 02 07 指针的步长(代码)

02 06 指针基本概念
02 07 指针的步长

指针
能解引用*(能代表它),被给了一个地址

空指针
没有写的权限

#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");
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值