指针做函数参数时,具备输入和输出特性:
输入特性:主调函数分配内存,被调函数使用
输出特性:被调函数分配内存,主调函数使用
1.输入特性
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void fun(char* p) {
strcpy(p, "hello world");
}
void test01() {
//输入特性 主函数分配内存
char buf[1024] = { 0 };
fun(buf);
printf("buf=%s\n", buf);
}
int main() {
test01(); // 输出hello world
system("pause");
return EXIT_SUCCESS;
}
在输入特性测试中,test01()函数为主调函数,在主调函数中分配内存,被调函数fun()传入指针作为参数,在被调函数中使用。
2.输出特性
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void fun(char** p) {
char* tmp = (char*)malloc(1024); //输出特性
if (tmp == NULL) {
return;
}
strcpy(tmp, "helloworld");
*p = tmp;
}
void test02() {
char* p = NULL;
fun(&p); // 传入指针地址
if (p != NULL) {
printf("%s\n", p);
free(p);
p = NULL;
}
}
int main() {
//test01(); // 输出hello world
test02(); // 输出helloworld
system("pause");
return EXIT_SUCCESS;
}
在输出特性测试案例中,主调函数test02(),被调函数fun(),我们在被调函数中申请分配内存,在使用被调函数并传入指针作为参数时,我们应该传入指针的地址作为参数,并且被调函数的形参为二级指针。