数组名作为实参传递给子函数时,其值弱化为指针

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. void change(char* d);
  5. void change(char* d) {
  6. *d = 'H';
  7. d[1] = 'E';
  8. *(d + 1) = 'L';
  9. }
  10. int main() {
  11. char c[6] = "hello";
  12. change(c);
  13. puts(c);
  14. return 0;
  15. }

image.png

指针与一维数组

在对函数进行传参时,我们可以用数组指针代替数组本身作为参数传递,因为传参过程中,数组弱化为指针;
其次对于已经开辟的内存空间,指针的本质还是寻址,并不会影响对数据的修改;

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. void change(char* d);
  5. void change(char* d) {
  6. *d = 'H';
  7. d[1] = 'E';
  8. *(d + 1) = 'L';
  9. }
  10. int main() {
  11. char c[6] = "hello";
  12. change(c);
  13. puts(c);
  14. return 0;
  15. }

指针与动态内存申请

  1. 数组一开始就已经定义,存放在栈空间;
  2. 程序是放在磁盘上的有序指令集合;
  3. 程序启动起来才叫做进程;

关键概念:进程地址空间

free() 释放内存空间

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. int main() {
  6. int i; // 用户定义的,可以申请的内存空间大小
  7. scanf("%d", &i);
  8. char* p;
  9. p = (char*)malloc(i); // malloc 申请空间的单位是字节
  10. strcpy(p, "malloc success");
  11. puts(p);
  12. free(p);
  13. return 0;
  14. }

image.png

malloc()函数

返回值的定义

  1. RETURN VALUE
  2. The malloc() and calloc() functions return a pointer to the allocated memory that is suitably aligned for any kind of variable.
  3. On error, these functions return NULL.
  4. 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.

堆栈的默认空间

image.png

free() 释放空间

image.png

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

image.png

栈和堆的区别

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. char* print_stack(void);
  5. char* print_malloc(void);
  6. char* print_stack(void)
  7. {
  8. char c[14] = "I am a Tiger!";
  9. puts(c);
  10. return c;
  11. }
  12. char* print_malloc(void)
  13. {
  14. char* q = (char*)malloc(12);
  15. strcpy(q, "I am a cat!");
  16. puts(q);
  17. return q;
  18. }
  19. int main()
  20. {
  21. char* p;
  22. char* q;
  23. p = print_stack(); // 栈空间会随着函数执行的结束而释放
  24. //puts(p);
  25. q = print_malloc(); // 堆空间不会随着函数执行的结束而释放,必须自行free()
  26. puts(q);
  27. free(q);
  28. q = NULL;
  29. return 0;
  30. }