堆区的注意事项(主调函数与被调函数之间的调用)

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

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

void test02()
{
	char *p = NULL;
	allocateSpace(p);
	printf("p=%s\n", p);
}

int main()
{
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

在这里插入图片描述
memset的用法

#include <stdio.h>
#include <string.h>
 
int main ()
{
   char str[50];
 
   strcpy(str,"This is string.h library function");
   puts(str);
 
   memset(str,'$',7);
   puts(str);
   
   return(0);
}
//打印后的结果如下所示:
//This is string.h library function
//$$$$$$$ string.h library function

**开始的时候,char *p和char pp在内存中开辟数据,然后在堆区申请一篇内存全直0,接着定义一个指针char temp来指向堆区的首地址。在文字常量区的值传入到堆区。
整个流程为以下三步,所以打印出来为NULL

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在test02()中我们一般叫它为主调函数,主调函数中这个指针为空,那么被调函数用同级的指针来修饰它,是修饰不成功的。那么想要改就要用二级指针。

接下来就是修改后的案例

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

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

void test02()
{
	char *p = NULL;
	allocateSpace(p);
	printf("p1=%s\n", p);
}

void allocateSpace2(char **pp)
{
	char *temp = malloc(100);
	memset(temp, 0, 100);
	strcpy(temp, "hello world");
	*pp = temp;
}

void test03()
{
	char *p = NULL;
	allocateSpace2(&p);
	printf("p2=%s\n", p);
}

int main()
{
	//test02();
	test03();
	system("pause");
	return EXIT_SUCCESS;
}

这里char pp存储的是p指针的地址,这就是与上面那一种不同的地方。看pp=temp这句话,pp指的是找到**pp解引用之后的数据,解出来的数据是0x01指向的数据也就是NULL,然后将temp赋给pp,temp存的地址为0x001
在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值