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

输入特性

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

输出特性

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

测试源码

#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;
}

测试结果

在这里插入图片描述

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

int  getMem(char **myp1/*out*/ , int *mylen1 /*out*/,  char **myp2 /*out*/, int *mylen2 /*out*/)
{
	int		ret = 0;
	char	*tmp1, *tmp2;

	tmp1 = (char *)malloc(100);
	strcpy(tmp1, "1132233");

	//间接赋值 
	*mylen1 = strlen(tmp1);  //1级指针
	*myp1 = tmp1; //2级指针的间接赋值

	tmp2 = (char *)malloc(200);
	strcpy(tmp2, "aaaaavbdddddddd");

	*mylen2 = strlen(tmp2);  //1级指针
	*myp2 = tmp2; //2级指针的间接赋值

	return ret;
}

char *  getMem1(int num)
{
	int		ret = 0;
	char	*tmp1;

	tmp1 = (char *)malloc(num);
	strcpy(tmp1, "1132233");

	return tmp1;
}

int  main(int argc, const char * argv[])
{
	int		ret = 0;
	char	*p1 = NULL;
	int		len1 = 0;
	char	*p2 = NULL;
	int		len2 = 0; 

	ret = getMem(&p1, &len1, &p2, &len2);
	if (ret != 0)
	{
		printf("func getMem41() err:%d \n", ret);
		return ret;
	}
	printf("p1:%s \n", p1);
	printf("p2:%s \n", p2);
	if (p1 != NULL)
	{
		free(p1);
		p1 = NULL;
	}
	if (p2 != NULL)
	{
		free(p2);
		p2 = NULL;
	}

	p1 = getMem1(100);
	printf("p1:%s \n", p1);
	if (p1 != NULL)
	{
		free(p1);
		p1 = NULL;
	}

	return ret;
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值