指针做函数参数的输入输出特性

输入特性

在主调函数中分配内存,被调函数使用

输出特性

被调函数中分配内存,主调函数使用

测试源码

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

//1、输入特性: 主调函数中分配内存,被调函数中使用内存
void func(char * p)
{
	strcpy(p, "hello world");
}

void test01()
{
	//分配到栈上
	char buf[1024] = { 0 };
	func(buf);

	printf("%s\n", buf);
}

void printString(char * str)
{
	printf("%s\n", str);

}

void test02()
{
	//分配到堆区
	char * p = malloc(sizeof(char)* 64);

	memset(p, 0, 64);

	strcpy(p, "hello world");

	printString(p);
	free(p);
}



//2、输出特性: 被调函数分配内存,主调函数使用内存

void allocateSpace(char ** pp)
{
	char * temp = malloc(sizeof(char)* 64);
	memset(temp, 0, 64);
	strcpy(temp, "hello world");
	*pp = temp;
}

void test03()
{
	char * p = NULL;
	allocateSpace(&p);

	printf("%s\n", p);
	free(p);

}


int main(){

	test01();
	test02();
	test03();

	system("pause");
	return EXIT_SUCCESS;
}

测试结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zxy131072/article/details/89641043
今日推荐