数组名作为实参传递给子函数时,其值弱化为指针
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>void change(char* d);void change(char* d) {*d = 'H';d[1] = 'E';*(d + 1) = 'L';}int main() {char c[6] = "hello";change(c);puts(c);return 0;}

指针与一维数组
在对函数进行传参时,我们可以用数组指针代替数组本身作为参数传递,因为传参过程中,数组弱化为指针;
其次对于已经开辟的内存空间,指针的本质还是寻址,并不会影响对数据的修改;
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>void change(char* d);void change(char* d) {*d = 'H';d[1] = 'E';*(d + 1) = 'L';}int main() {char c[6] = "hello";change(c);puts(c);return 0;}
指针与动态内存申请
- 数组一开始就已经定义,存放在栈空间;
- 程序是放在磁盘上的有序指令集合;
- 程序启动起来才叫做进程;
关键概念:进程地址空间
free() 释放内存空间
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>#include <string.h>int main() {int i; // 用户定义的,可以申请的内存空间大小scanf("%d", &i);char* p;p = (char*)malloc(i); // malloc 申请空间的单位是字节strcpy(p, "malloc success");puts(p);free(p);return 0;}

malloc()函数
返回值的定义
RETURN VALUEThe malloc() and calloc() functions return a pointer to the allocated memory that is suitably aligned for any kind of variable.On error, these functions return NULL.NULL may also be returned by a successful call to malloc() with a size of zero, or by a successful call to calloc() with nmemb or size equal to zero.
堆栈的默认空间

free() 释放空间

不能在申请空间后再次偏移指针

栈和堆的区别
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>char* print_stack(void);char* print_malloc(void);char* print_stack(void){char c[14] = "I am a Tiger!";puts(c);return c;}char* print_malloc(void){char* q = (char*)malloc(12);strcpy(q, "I am a cat!");puts(q);return q;}int main(){char* p;char* q;p = print_stack(); // 栈空间会随着函数执行的结束而释放//puts(p);q = print_malloc(); // 堆空间不会随着函数执行的结束而释放,必须自行free()puts(q);free(q);q = NULL;return 0;}
