指针基础
指针和内存单元
- 指针: 地址。
- 内存单元: 计算机中内存最小的存储单位。——内存单元。大小一个字节。 每一个内存单元都有一个唯一的编号(数)。 称这个内存单元的编号为 “地址”。
- 指针变量:存地址的变量。
指针定义和使用:
int a = 10;
int *p = &a;
int* p;--- windows;
int *p ---Linux int * p ;
int a, *p, *q, b;
*p = 250; 指针的 解引用。 间接引用。
*p : /*将p变量的内容取出,当成地址看待,找到该地址对应的内存空间。
如果做左值: 存数据到空间中。
如果做右值: 取出空间中的内容。*/
int a = 10;
int *p = &a;
//*p = 2000;
a = 350;
//printf("a = %d\n", a);
printf("*p = %d\n", *p);
printf("sizeof(int *) = %u\n", sizeof(int *));
printf("sizeof(short *) = %u\n", sizeof(short *));
printf("sizeof(char *) = %u\n", sizeof(char *));
printf("sizeof(long *) = %u\n", sizeof(long *));
printf("sizeof(double *) = %u\n", sizeof(double *));
printf("sizeof(void *) = %u\n", sizeof(void *));
system("pause");
return EXIT_SUCCESS;
任意“指针”类型大小:
- 指针的大小与类型 无关。 只与当前使用的平台架构有关。 32位:4字节。 64位: 8字节。
野指针:
- 没有一个有效的地址空间的指针。
int *p;
*p = 1000;
- p变量有一个值,但该值不是可访问的内存区域。
int *p = 10;
*p = 2000;
【杜绝野指针】
空指针:
int *p = NULL; #define NULL ((void *)0)
*p 时 p所对应的存储空间一定是一个 无效的访问区域。
- 示例:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// 野指针1
int main0201(void)
{
/*
int *p;
*p = 2000;
printf("*p = %d\n", *p);
*/
system("pause");
return EXIT_SUCCESS;
}
// 野指针2
int main0202(void)
{
int m;
//int *p = 1000; // 0-255 确定留给操作系统
int *p = 0x0bfcde0000;
p = &m;
*p = 2000;
printf("*p = %d\n", *p);
system("pause");
return EXIT_SUCCESS;
}
// 空指针
int main0203(void)
{
int *p = NULL; // NULL == 0
// .....
// lllll
// .....
if (p != NULL)
{
*p = 300;
printf("*p = %d\n", *p);
}
system("pause");
return EXIT_SUCCESS;
}
万能指针/泛型指针(void *):
- 可以接收任意一种变量地址。但是,在使用【必须】借助“强转”具体化数据类型。
- char ch = 'R';
- void *p; // 万能指针、泛型指针
- p = &ch;
- printf("%c\n", *(char *)p);
实例:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// 野指针1
int main0201(void)
{
/*
int *p;
*p = 2000;
printf("*p = %d\n", *p);
*/
system("pause");
return EXIT_SUCCESS;
}
// 野指针2
int main0202(void)
{
int m;
//int *p = 1000; // 0-255 确定留给操作系统
int *p = 0x0bfcde0000;
p = &m;
*p = 2000;
printf("*p = %d\n", *p);
system("pause");
return EXIT_SUCCESS;
}
// 空指针
int main0203(void)
{
int *p = NULL; // NULL == 0
// .....
// lllll
// .....
if (p != NULL)
{
*p = 300;
printf("*p = %d\n", *p);
}
system("pause");
return EXIT_SUCCESS;
}
const关键字:
- 修饰变量:
const int a = 20;
int *p = &a;
*p = 650;
printf("%d\n", a);
- 修饰指针:
可以修改 p
不可以修改 *p。
int const *p;
同上。
int * const p;
可以修改 *p
不可以修改 p。
const int *const p;
不可以修改 p。
不可以修改 *p。
- 总结:const 向右修饰,被修饰的部分即为只读。
- 常用:在函数形参内,用来限制指针所对应的内存空间为只读。