Skip to content

指针

内存含义

  • 存储器:计算机的组成中,用来存储程序和数据,辅助CPU进行运算处理的重要部分。
  • 内存:内部存贮器,暂存程序/数据——掉电丢失 SRAM、DRAM、DDR、DDR2、DDR3。
  • 外存:外部存储器,长时间保存程序/数据—掉电不丢ROM、ERRROM、FLASH (NAND、NOR)、硬盘、光盘。

内存是沟通CPU与硬盘的桥梁

  • 暂存放CPU中的运算数据
  • 暂存与硬盘等外部存储器交换的数据

物理存储器和存储地址空间

有关内存的两个概念:物理存储器和存储地址空间。

物理存储器:实际存在的具体存储器芯⽚。

  • 主板上装插的内存条
  • 显⽰卡上的显⽰RAM芯⽚
  • 各种适配卡上的RAM芯⽚和ROM芯⽚

存储地址空间:对存储器编码的范围。我们在软件上常说的内存是指这一层含义。

  • 编码:对每个物理存储单元(一个字节)分配一个号码
  • 寻址:可以根据分配的号码找到相应的存储单元,完成数据的读写

内存地址

将内存抽象成一个很⼤的一维字符数组。编码就是对内存的每一个字节分配一个32位或64位的编号(与32位或者64位处理器相关)。这个内存编号我们称之为内存地址。

内存中的每一个数据都会分配相应的地址:

  • char:占一个字节分配一个地址
  • int: 占四个字节分配四个地址
  • floatstruct、函数、数组等

指针和指针变量

  • 如果在程序中定义了一个变量,在对程序进行编译或运行时,系统就会给这个变量分配内存单元,并确定它的内存地址(编号)
  • 指针的实质就是内存“地址”。指针就是地址,地址就是指针。
  • 通常我们叙述时会把指针变量简称为指针,实际他们含义并不一样。

指针是一种数据类型,占用内存空间,用来保存内存地址。

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void test() {
    int *p1 = 0x1234;
    int ***p2 = 0x1111;
    printf("p1 size:%d\n", sizeof(p1));
    printf("p2 size:%d\n", sizeof(p2));//指针是变量,指针本⾝也占内存空间,指针也可以被赋值

    int a = 10;
    p1 = &a;

    printf("p1 address:%p\n", &p1);
    printf("p1 address:%p\n", p1);
    printf("a address:%p\n", &a);
}

int main(void) {
    test();

    return 0;
}

程序输出:

shell
p1 size:8
p2 size:8
p1 address:0x7fffffffe3d8
p1 address:0x7fffffffe3cc
a address:0x7fffffffe3cc

指针变量的定义和使用

  • 指针变量指向谁,就把谁的地址赋值给指针变量
  • *操作符操作的是指针变量指向的内存空间
c
#include <stdio.h>

int main(){
    int a = 0;
    char b = 100;
    printf("a=%d, &a=%p\n", a, &a);
    printf("b=%c, &b=%p\n", b, &b);

    int *p;
    // int *代表一种数据类型,int *指针类型,p才是变量名
    // 定义了一个指针类型的变量,可以指向一个int类型变量的地址
    
    p = &a;
    // 将a的地址赋值给变量p。p也是一个变量,值是一个内存地址编号
    putchar('\n');
    printf("p=%x, &p=%p, *p=%d\n", p, &p, *p);
    // p指向了a的地址,*p就是a的值

    char *p1 = &b;
    printf("p1=%x, &p1=%p, *p1=%c\n", p1, &p1, *p1);
    // p1指向了b的地址,*p1就是b的值

    return 0;
}

程序输出:

shell
a=0, &a=0x16d7575b8
b=d, &b=0x16d7575b7

p=6d7575b8, &p=0x16d7575a8, *p=0
p1=6d7575b7, &p1=0x16d7575a0, *p1=d

⚠️ 注意

&可以取得一个变量在内存中的地址。但是,,因为寄存器变量不在 内存里,而在CPU里⾯,所以是没有地址的。

间接访问操作符

通过一个指针访问它所指向的地址的过程叫做间接访问,或者叫解引用指针,这个用于执行间接访问的操作符是*。

注意:对一个int*类型指针解引用会产生一个整型值,类似地,对一个float*指针解引用会产生了一个float类型的值。

  • 在指针声明时, * 号表⽰所声明的变量为指针
  • 在指针使用时, * 号表⽰操作指针所指向的内存空间
    • **相当通过地址(指针变量的值)找到指针指向的内存,再操作内存
    • * 放在等号的左边赋值(给内存赋值,写内存)
    • * 放在等号的右边取值(从内存中取值,读内存)
c
#include <stdio.h>
#include <stdlib.h>

//解引用
void test01() {//定义指针
    int *p = NULL;
    //指针指向谁,就把谁的地址赋给指针
    int a = 10;
    p = &a;
    *p = 20;//*在左边当左值,必须确保内存可写
    //*号放右⾯,从内存中读值
    int b = *p;//必须确保内存可写
    char *str = "hello world!";
    *str = 'm';

    printf("a:%d\n", a);
    printf("*p:%d\n", *p);
    printf("b:%d\n", b);
}

int main(void) {
    test01();

    return 0;
}

错误使用指针引发程序异常

通过指针间接修改变量的值

c
#include <stdio.h>

int main(){
    int a = 0;
    int b = 11;
    int *p = &a;
    printf("修改前:\na=%d, b=%d\n", a, b);

    *p = 100;
    puts("\n修改后");
    printf("a=%d, *p=%d\n", a, *p);

    p = &b;
    *p = 22;
    printf("b=%d, *p=%d\n", b, *p);

    return 0;
}

程序输出:

shell
修改前:
a=0, b=11

修改后
a=100, *p=100
b=22, *p=22

指针大小

  • sizeof()测的是指针变量指向存储地址的⼤⼩
  • 在32位平台,所有的指针(地址)都是32位(4字节)
  • 在64位平台,所有的指针(地址)都是64位(8字节)
c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *p1;
    int **p2;
    char *p3;
    char **p4;
    printf("sizeof(p1) = %d\n", sizeof(p1));
    printf("sizeof(p2) = %d\n", sizeof(p2));
    printf("sizeof(p3) = %d\n", sizeof(p3));
    printf("sizeof(p4) = %d\n", sizeof(p4));
    printf("sizeof(double *) = %d\n", sizeof(double *));

    return 0;
}

程序输出:

shell
sizeof(p1) = 8
sizeof(p2) = 8
sizeof(p3) = 8
sizeof(p4) = 8
sizeof(double *) = 8

野指针和空指针

指针变量也是变量,是变量就可以任意赋值,不要越界即可(32位为4字节,64位为8字节),但是,,此指针指向的区域是未知(操作系统不允许操作此指针指向的内存区域)。

c
int a = 100; 
int *p; 
p = a; //把a的值赋值给指针变量p,p为野指针, ok,不会有问题,但没有意义

p = 0x12345678; //给指针变量p赋值,p为野指针, ok,不会有问题,但没有意义

*p = 1000; //操作野指针指向未知区域,内存出问题,err

但是,野指针和有效指针变量保存的都是数值,为了标志此指针变量没有指向任何变量(空闲可用),C语⾔中,可以把NULL赋值给此指针,这样就标志此指针为空指针,没有任何指针。

int *p = NULL;

NULL是一个值为0的宏常量: #define NULL ((void *)0)

TIP

野指针指向一个已删除的对象或未申请访问受限内存区域的指针。与空指针不同,野指针⽆法通过简单地判断是否为 NULL避免,而只能通过养成良好的编程习惯来尽力减少。

什么情况下会导致野指针?

  • 指针变量未初始化

    任何指针变量刚被创建时不会⾃动成为NULL指针,它的缺省值是随机的,它会乱指一⽓。所以,指针变量在创建的同时应当被初始化,要么将指针设置为NULL,要么让它指向合法的内存。

  • 指针释放后未置空

    有时指针在free或delete后未赋值 NULL,便会使人以为是合法的。别看free和delete的名字(尤其是delete),它们只是把指针所指的内存给释放掉,但并没有把指针本⾝⼲掉。此时指针指向的就是“垃圾”内存。释放后的指针应⽴即将指针置为NULL,防⽌产生“野指针”。

  • 指针操作超越变量作用域

    不要返回指向栈内存的指针或引用,因为栈内存在函数结束时会被释放。

示例
cpp
#include <stdio.h>
#include <stdlib.h>

void test() {
    int *p = 0x001;//未初始化
    printf("%p\n", p);
    *p = 100;
}

int main(void) {
    test();

    return 0;
}

操作野指针是非常危险的操作,应该规避野指针的出现:

  • 初始化时置 NULL

    指针变量一定要初始化为NULL,因为任何指针变量刚被创建时不会⾃动成为NULL指针,它的缺省值是随机的。

  • 释放时置 NULL

    当指针p指向的内存空间释放时,没有设置指针p的值为NULL。delete和free只是把内存空间释放了,但是并没有将指针p的值赋为NULL。通常判断一个指针是否合法,都是使用if语句测试该指针是否为NULL。

标准定义了NULL指针,它作为一个特殊的指针变量,表⽰不指向任何东西。要使一个指针为NULL,可以给它赋值一个零值。为了测试一个指针百年来那个是否为NULL,你可以将它与零值进行比较。

对指针解引用操作可以获得它所指向的值。但从定义上看,NULL指针并未指向任何东西,因为对一个NULL指针因引用是一个非法的操作,在解引用之前,必须确保它不是一个NULL指针。

如果对一个NULL指针间接访问会发生什么呢?结果因编译器而异。

不允许向NULL和非法地址拷贝内存:

c
#include <stdio.h>
#include <stdlib.h>

void test() {
    char *p = NULL;
    //给p指向的内存区域拷贝内容
    strcpy(p, "1111");//err
    char *q = 0x1122;
    //给q指向的内存区域拷贝内容
    strcpy(q, "2222");//err
}

int main(void) {
    test();

    return 0;
}

泛型指针(万能指针)void *

void *指针也叫做万能指针、泛型指针。可以指向任意变量的内存空间:

c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    void *p = NULL;

    int a = 10;
    p = (void *) &a;//指向变量时,最好转换为void *

    //使用指针变量指向的内存时,转换为int *
    *((int *) p) = 11;
    printf("a = %d\n", a);

    return 0;
}

程序输出:

shell
a = 11

指针的步长

指针是一种数据类型,是指它指向的内存空间的数据类型。指针所指向的内存空间决定了指针的步长。指针的步长指的是,当指针+1时候,移动多少字节单位。

思考如下问题:

c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int a = 0xaabbccdd;
    unsigned int *p1 = &a;
    unsigned char *p2 = &a;

    //为什么*p1打印出来正确结果?
    printf("%x\n", *p1);
    //为什么*p2没有打印出来正确结果?
    printf("%x\n", *p2);
    //为什么p1指针+1加了4字节?
    printf("p1 =%d\n", p1);
    printf("p1+1=%d\n", p1 + 1);
    //为什么p2指针+1加了1字节?
    printf("p2 =%d\n", p2);
    printf("p2+1=%d\n", p2 + 1);

    return 0;
}

程序输出:

shell
aabbccdd
dd
p1 =-7176
p1+1=-7172
p2 =-7176
p2+1=-7175

const修饰的指针变量

c
int a = 100; 
int b = 200;

//指向常量的指针 
//修饰*,指针指向内存区域不能修改,指针指向可以变 
const int * p1 = &a; //等价于int const *p1 = &a; 
//*p1 = 111; //err 
p1 = &b; //ok

//指针常量 
//修饰p1,指针指向不能变,指针指向的内存可以修改 
int * const p2 = &a; 
//p2 = &b; //err 
*p2 = 222; //ok
c
#include <stdio.h>
#include <stdlib.h>

//const修饰变量
void test01() {

    //1. const基本概念
    const int i = 0;//i = 100; //错误,只读变量初始化之后不能修改

    //2. 定义const变量最好初始化
    const int j;
    //j = 100; //错误,不能再次赋值

    //3. c语⾔的const是一个只读变量,并不是一个常量,可通过指针间接修改
    const int k = 10;//k = 100; //错误,不可直接修改,我们可通过指针间接修改
    printf("k:%d\n", k);

    int *p = &k;
    *p = 100;
    printf("k:%d\n", k);
}

//const 修饰指针
void test02() {
    int a = 10;
    int b = 20;
    //const放在*号左侧 修饰p_a指针指向的内存空间不能修改,但可修改指针的指向
    const int *p_a = &a;
    //*p_a = 100; //不可修改指针指向的内存空间
    p_a = &b;//可修改指针的指向
    //const放在*号的右侧, 修饰指针的指向不能修改,但是可修改指针指向的内存空间
    int *const p_b = &a;
    //p_b = &b; //不可修改指针的指向
    *p_b = 100;//可修改指针指向的内存空间
    //指针的指向和指针指向的内存空间都不能修改
    const int *const p_c = &a;
}

//const指针用法
struct Person {
    char name[64];
    int id;
    int age;
    int score;
};

//每次都对对象进行拷贝,效率低,应该用指针
void printPersonByValue(struct Person person) {
    printf("Name:%s\n", person.name);
    printf("Name:%d\n", person.id);
    printf("Name:%d\n", person.age);
    printf("Name:%d\n", person.score);
}

//但是用指针会有副作用,可能会不⼩⼼修改原数据
void printPersonByPointer(const struct Person *person) {
    printf("Name:%s\n", person->name);
    printf("Name:%d\n", person->id);
    printf("Name:%d\n", person->age);
    printf("Name:%d\n", person->score);
}

void test03() {
    struct Person p = {"Obama", 1101, 23, 87};
    //printPersonByValue(p);
    printPersonByPointer(&p);
}

int main(void) {
    printf("test01 print:\n");
    test01();
    printf("\n\ntest02 print:\n");
    test02();
    printf("\n\ntest03 print:\n");
    test03();

    return 0;
}

程序输出:

shell
test01 print:
buf:aaaa


test02 print:
buf:123456a


test03 print:
buf:abcdefg
test01 print:
k:10
k:10


test02 print:


test03 print:
Name:Obama
Name:1101
Name:23
Name:87

多级指针

C语⾔允许有多级指针存在,在实际的程序中一级指针最常用,其次是二级指针。二级指针就是指向一个一级指针变量地址的指针。三级指针基本用不着,但考试会考。

c
int a = 10; 
int *p = &a; //一级指针
*p = 100; //*p就是a

int **q = &p; //*q就是p //**q就是a

int ***t = &q; //*t就是q //**t就是p //***t就是a

指针的意义——间接赋值

间接赋值的三大条件

通过指针间接赋值成⽴的三⼤条件:

  1. 2个变量(一个普通变量一个指针变量、或者一个实参一个形参)
  2. 建⽴关系
  3. 通过 * 操作指针指向的内存
c
void test() {
    int a = 100; //两个变量
    int* p = NULL;
    //建⽴关系 
    //指针指向谁,就把谁的地址赋值给指针
    p = &a;
    //通过*操作内存
    *p = 22;
}

如何定义合适的指针变量

c
void test() { 
    int b;
    int* q = &b; //0级指针
    int** t = &q;
    int*** m = &t;
}

间接赋值:从0级指针到1级指针

c
#include <stdio.h>
#include <stdlib.h>

int func1() { return 10; }
void func2(int a) {
    a = 100;
}

//指针的意义_间接赋值
void test02() {
    int a = 0;
    a = func1();
    printf("a = %d\n", a);
    //为什么没有修改?
    func2(a);
    printf("a = %d\n", a);
}

//指针的间接赋值
void func3(int *a) {
    *a = 100;
}
void test03() {
    int a = 0;
    a = func1();
    printf("a = %d\n", a);

    //修改
    func3(&a);
    printf("a = %d\n", a);
}

int main(void) {
    printf("test02 print:\n");
    test02();
    printf("\n\ntest03 print:\n");
    test03();

    return 0;
}

程序输出:

shell
test02 print:
a = 10
a = 10


test03 print:
a = 10
a = 100

间接赋值:从1级指针到2级指针

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void AllocateSpace(char **p) {
    *p = (char *) malloc(100);
    strcpy(*p, "hello world!");
}

void FreeSpace(char **p) {
    if (p == NULL) { return; }
    if (*p != NULL) {
        free(*p);
        *p = NULL;
    }
}

void test() {
    char *p = NULL;
    AllocateSpace(&p);
    printf("%s\n", p);
    FreeSpace(&p);
    if (p == NULL) { printf("p内存释放!\n"); }
}
int main(void) {
    test();

    return 0;
}

程序输出:

shell
hello world!
p内存释放!

间接赋值的推论

  • 用1级指针形参,去间接修改了0级指针(实参)的值。
  • 用2级指针形参,去间接修改了1级指针(实参)的值。
  • 用3级指针形参,去间接修改了2级指针(实参)的值。
  • 用n级指针形参,去间接修改了n-1级指针(实参)的值。

指针和数组

数组名

数组名字是数组的⾸元素地址,但它是一个地址常量:

c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    printf("a = %p\n", a);
    printf("&a[0] = %p\n", &a[0]);

    //a = 10; //err, 数组名只是常量,不能修改

    return 0;
}

程序输出:

shell
a = 0x7fffffffe3d0
&a[0] = 0x7fffffffe3d0

指针操作数组元素

c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int i = 0;
    int n = sizeof(a) / sizeof(a[0]);

    for (i = 0; i < n; i++) {
        //printf("%d, ", a[i]);
        printf("%d, ", *(a + i));
    }
    printf("\n");

    int *p = a;//定义一个指针变量保存a的地址
    for (i = 0; i < n; i++) {
        p[i] = 2 * i;
    }

    for (i = 0; i < n; i++) {
        printf("%d, ", *(p + i));
    }
    printf("\n");

    return 0;
}

程序输出:

shell
1, 2, 3, 4, 5, 6, 7, 8, 9, 
0, 2, 4, 6, 8, 10, 12, 14, 16,

指针加减运算

加法运算

  • 如果是一个 int * ,+1的结果是增加一个int的⼤⼩
  • 如果是一个 char * ,+1的结果是增加一个char⼤⼩
c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int a;
    int *p = &a;
    printf("%d\n", p);
    p += 2;//移动了2个int
    printf("%d\n", p);

    char b = 0;
    char *p1 = &b;
    printf("%d\n", p1);
    p1 += 2;
    printf("%d\n", p1);

    return 0;
}

程序输出:

shell
-7176
-7168
-7185
-7183

通过改变指针指向操作数组元素:

c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int i = 0;
    int n = sizeof(a) / sizeof(a[0]);

    int *p = a;
    for (i = 0; i < n; i++) {
        printf("%d, ", *p);
        p++;
    }
    printf("\n");

    return 0;
}

程序输出:

shell
1, 2, 3, 4, 5, 6, 7, 8, 9,

减法运算

示例1

c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int i = 0;
    int n = sizeof(a) / sizeof(a[0]);

    int *p = a + n - 1;
    for (i = 0; i < n; i++) {
        printf("%d, ", *p);
        p--;
    }
    printf("\n");

    return 0;
}

程序输出:

shell
9, 8, 7, 6, 5, 4, 3, 2, 1,

示例2

c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int *p2 = &a[2];//第3个元素地址
    int *p1 = &a[1];//第2个元素地址
    printf("p1 = %p\np2 = %p\n", p1, p2);

    int n1 = p2 - p1;//n1 = 1
    int n2 = (int) p2 - (int) p1;//n2 = 4
    printf("n1 = %d, n2 = %d\n", n1, n2);

    return 0;
}

程序输出:

shell
p1 = 0x7fffffffe3d4
p2 = 0x7fffffffe3d8
n1 = 1, n2 = 4

指针数组

指针数组,它是数组,数组的每个元素都是指针类型。

c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    //指针数组
    int *p[3];
    int a = 1;
    int b = 2;
    int c = 3;
    int i = 0;

    p[0] = &a;
    p[1] = &b;
    p[2] = &c;

    for (i = 0; i < sizeof(p) / sizeof(p[0]); i++) {
        printf("%d, ", *(p[i]));
    }
    printf("\n");

    return 0;
}

程序输出:

shell
1, 2, 3,

指针和字符串

字符指针

c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char str[] = "hello world";
    char *p = str;
    *p = 'm';
    p++;
    *p = 'i';
    printf("%s\n", str);

    p = "mike jiang";
    printf("%s\n", p);

    char *q = "test";
    printf("%s\n", q);

    return 0;
}

程序输出:

shell
millo world
mike jiang
test

字符指针做函数参数

c
#include <stdio.h>
#include <stdlib.h>

void mystrcat(char *dest, const char *src) {
    int len1 = 0;
    int len2 = 0;
    while (dest[len1]) { len1++; }
    while (src[len2]) { len2++; }
    int i;
    for (i = 0; i < len2; i++) {
        dest[len1 + i] = src[i];
    }
}

int main(void) {
    char dst[100] = "hello mike";
    char src[] = "123456";

    mystrcat(dst, src);
    printf("dst = %s\n", dst);

    return 0;
}

程序输出:

shell
dst = hello mike123456

指针数组做为main函数的形参

c
int main(int argc, char *argv[]);
  • main函数是操作系统调用的,第一个参数标明argc数组的成员数量,argv数组的每个成员都是char *类型
  • argv是命令行参数的字符串数组
  • argc代表命令行参数的数量,程序名字本⾝算一个参数
c
#include <stdio.h>
#include <stdlib.h>

//argc: 传参数的个数(包含可执行程序)
//argv:指针数组,指向输⼊的参数
int main(int argc, char *argv[]) {
    //指针数组,它是数组,每个元素都是指针
    char *a[] = {"aaaaaaa", "bbbbbbbbbb", "ccccccc"};
    int i = 0;

    printf("argc = %d\n", argc);
    for (i = 0; i < argc; i++) {
        printf("%s\n", argv[i]);
    }

    return 0;
}

程序输出:

shell
argc = 1
/home/morax/code/Build_files/format.out

const修饰的指针变量

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    //const修饰一个变量为只读
    const int a = 10;
    //a = 100; //err

    //指针变量, 指针指向的内存, 2个不同概念
    char buf[] = "aklgjdlsgjlkds";
    //从左往右看,跳过类型,看修饰哪个字符
    //如果是*, 说明指针指向的内存不能改变
    //如果是指针变量,说明指针的指向不能改变,指针的值不能修改
    const char *p = buf;
    // 等价于上⾯ char const *p1 = buf;
    //p[1] = '2'; //err
    p = "agdlsjaglkdsajgl";//ok

    char *const p2 = buf;
    p2[1] = '3';
    //p2 = "salkjgldsjaglk"; //err

    //p3为只读,指向不能变,指向的内存也不能变
    const char* const p3 = buf;

    return 0;
}

指针和函数

函数形参改变实参的值

c
#include <stdio.h>
#include <stdlib.h>

void swap1(int x, int y) {
    int tmp;
    tmp = x;
    x = y;
    y = tmp;
    printf("a1 = %d, b1 = %d\n", x, y);
}

void swap2(int *x, int *y) {
    int tmp;
    tmp = *x;
    *x = *y;
    *y = tmp;
}

int main(void) {
    int a = 3;
    int b = 5;
    swap1(a, b);//值传递
    printf("a = %d, b = %d\n", a, b);

    a = 3;
    b = 5;
    swap2(&a, &b);//地址传递 
    printf("a2 = %d, b2 = %d\n", a, b);

    return 0;
}

程序输出:

shell
a1 = 5, b1 = 3
a = 3, b = 5
a2 = 5, b2 = 3

数组名做函数参数

c
#include <stdio.h>
#include <stdlib.h>

void printArrary(int *a, int n) {
    int i = 0;
    for (i = 0; i < n; i++) {
        printf("%d, ", a[i]);
    }
    printf("\n");
}
int main(void) {
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int n = sizeof(a) / sizeof(a[0]);

    //数组名做函数参数
    printArrary(a, n);

    return 0;
}

程序输出:

shell
1, 2, 3, 4, 5, 6, 7, 8, 9,

指针做函数参数

指针做函数参数,具备输⼊和输出特性:

  • 输⼊:主调函数分配内存
  • 输出:被调用函数分配内存

输入特性

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void fun(char *p /* in */) {
    //给p指向的内存区域拷贝内容
    strcpy(p, "abcddsgsd");
}

void test(void) {
    //输⼊,主调函数分配内存
    char buf[100] = {0};
    fun(buf);
    printf("buf = %s\n", buf);
}

int main(void) {
    test();

    return 0;
}

程序输出:

shell
buf = abcddsgsd

输出特性

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void fun(char **p /* out */, int *len) {
    char *tmp = (char *) malloc(100);
    if (tmp == NULL) { return; }
    strcpy(tmp, "adlsgjldsk");
    //间接赋值
    *p = tmp;
    *len = strlen(tmp);
}

void test(void) {
    //输出,被调用函数分配内存,地址传递
    char *p = NULL;
    int len = 0;
    fun(&p, &len);
    if (p != NULL) { printf("p = %s, len = %d\n", p, len); }
}

int main(void) {
    test();

    return 0;
}

程序输出:

shell
p = adlsgjldsk, len = 10

指针做为函数的返回值

c
#include <stdio.h>
#include <stdlib.h>

int a = 10;
int *getA() { return &a; }

int main(void) {
    *(getA()) = 111;
    printf("a = %d\n", a);

    return 0;
}

程序输出:

shell
a = 111

指针小结

定义说明
int i定义整形变量
int *p定义一个指向int的指针变量
int a[10]定义一个有10个元素的数组,每个元素类型为int
int *p[10]定义一个有10个元素的数组,每个元素类型为int*
int func()定义一个函数,返回值为int型
int *func()定义一个函数,返回值为int *型
int **p定义一个指向int的指针的指针,二级指针

一级指针易错点

越界

c
#include <stdio.h>
#include <stdlib.h>

void test() {
    char buf[3] = "abc";
    printf("buf:%s\n", buf);
}

int main(void) {
    test();

    return 0;
}

程序输出:

shell
buf:abc烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫

指针叠加会不断改变指针指向

c
#include <stdio.h>
#include <stdlib.h>

void test() {
    char *p = (char *) malloc(50);
    char buf[] = "abcdef";
    int n = strlen(buf);
    int i = 0;

    for (i = 0; i < n; i++) {
        *p = buf[i];
        p++;//修改原指针指向
    }
    free(p);
}

int main(void) {
    test();

    return 0;
}

返回局部变量地址

c
#include <stdio.h>
#include <stdlib.h>

char *get_str() {
    char str[] = "abcdedsgads";//栈区,
    printf("[get_str]str = %s\n", str);
    return str;
}

int main(void) {
    char *p = NULL;
    p = get_str();
    printf("str=[%s]\n", p);

    return 0;
}

同一块内存释放多次(不可以释放野指针)

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void test() {
    char *p = NULL;
    p = (char *) malloc(50);
    strcpy(p, "abcdef");
    if (p != NULL) {
        //free()函数的功能只是告诉系统 p 指向的内存可以回收了
        // 就是说,p 指向的内存使用权交还给系统
        //但是,p的值还是原来的值(野指针),p还是指向原来的内存
        free(p);
    }

    if (p != NULL) {
        free(p);
    }
}

int main(void) {
    test();

    return 0;
}