c语言指针面试

1,

#include
#include
#include

void GetMemory1(char* str,int num)
{
	str = (char*)malloc(num*sizeof(char));
	if(str == NULL)
	{
		printf("malloc memory failed\n");
	}
}

char* GetMemory2(int num)
{
	char* str =(char*)malloc(num*sizeof(char));
	if(str == NULL)
	{
		printf("malloc memory failed\n");
		return NULL;
	}
	return str;
}

void GetMemory3(char** str,int num)
{
	*str = (char*)malloc(num*sizeof(char));
	if(*str == NULL)
	{
		printf("malloc memory failed\n");
	}
}


int main()
{
	char* s1 = NULL;
	char* s2 = NULL;
	char* s3 = NULL;
#if 0
	GetMemory1(s1,10);
	strcpy(s1,"hello");
	printf("s1= %s\n",s1);
	free(s1);
#endif
	s2 = GetMemory2(10);
	strcpy(s2,"hello");
	printf("s2=%s\n",s2);
	free(s2);

	GetMemory3(&s3,10);
	strcpy(s3,"hello");
	printf("s3=%s\n",s3);
	free(s3);

	return 0;
}

在GetMemory1函数中malloc申请了内存,但是调用了之后没有保存,所以我们调用了之后还是空指针,我们这里要么用二级指针或者用指针返回值。

 

你可能感兴趣的:(c语言基础)