函数形参参数二级指针Demo图
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
void func2(char** out_ptr) {
char* p = (char*)malloc(sizeof(char) * 128);
//p = "world";
memset(p, 0, sizeof(char) * 128);
strcpy(p, "world");
*out_ptr = p;
}
int main() {
char* b;
func2(&b);
printf("string b is: %s\n", b);
free(b);
b = NULL;
return 0;
}
输出结果:
string b is: world
函数形参参数二级指针Demo图如下:
C程序内存图如下:
函数形参参数一级指针和二级指针Demo
函数形参参数一级指针和二级指针Demo
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
void func(char* ptr) {
printf("%s\n", ptr);
ptr[0] = 'e';
}
void func2(char** out_ptr) {
char* p = (char*)malloc(sizeof(char) * 128);
//p = "world";
memset(p, 0, sizeof(char) * 128);
strcpy(p, "world");
*out_ptr = p;
}
int main() {
char* a = (char *)malloc(sizeof(char) * 128);
strcpy(a, "hello");
func(a);
printf("string a is: %s\n", a);
printf("before free a, Address is: %p,String is: %s\n", a, a);
free(a); // 使用完之后,记得释放堆内存,避免内存泄露
printf("after free a, Address is: %p, String is: %s\n", a, a);
a = NULL; // free(a)之后,记得把a赋值为NULL,避免野指针。
printf("after free a and a = NULL, Address is: %p, String is: %s\n", a, a);
char* b;
func2(&b);
printf("string b is: %s\n", b);
printf("before free b, Address is: %p,String is: %s\n", b, b);
free(b);
printf("after free b, Address is: %p, String is: %s\n", b, b);
b = NULL;
printf("after free a and a = NULL, Address is: %p, String is: %s\n", b, b);
return 0;
}