现在的位置: 首页 > 综合 > 正文

使用指向指针的指针进行动态内存分配

2018年03月20日 ⁄ 综合 ⁄ 共 435字 ⁄ 字号 评论关闭
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
void getMemory(char *p,int num)
{
	//这里实质是对str的形参p进行操作,函数结束后,str的值认为Null
	p = (char*)malloc(sizeof(char)*num);
}

int main()
{
	char *str = NULL;
	getMemory(str,100);
	strcpy(str,"hello world");
	printf("%s\n",str);
	return 0;
}
*/

void getMemory(char **p,int num)
{
	//这里实质上是对指针str进行操作
	*p = (char*)malloc(sizeof(char)*num);
}

int main()
{
	char *str = NULL;
	getMemory(&str,100);
	strcpy(str,"hello world");
	printf("%s\n",str);
	return 0;
}

抱歉!评论已关闭.