C语言面试题之——getmemory


/*
Filename:		getmemory.c
Version:		0.0.1
Date:			11-02-2012 12:58

Description:	use malloc() ,free() to apply for a serials internal memory, then use strcpy() to copy a C-string to this space, use pointer to access the memory.
无法把指针变量本身传递给一个函数。

	以上参考《C语言深度剖析》及网络
	
Compiler:			MinGW GCC 4.6.1 32-bits
Test environment:	codelite v3.5.5377 @2007-2012, By Eran Ifrah
*/


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

void get_memory( char **p, int num);
char *Get_memory(char *p, int num);


char *Get_memory(char *p, int num)
{
	p = (char*)malloc(num *sizeof(char));
	return p;
}

void get_memory( char **p, int num)
{
	*p = (char*)malloc(num * sizeof(char));
	//return p;
}

/*char *get_memo(void)
{
	char p[] = "Hello,World";
	return p;
	//函数中的局部变量存放在stack中,函数执行完成之后会自动释放,因此不应将局 部变量的指针作为返回值。 
}*/
//可以使用下面的方法来解决这种问题
char *get_str()
{
	char *str = (char *)malloc(512);
	memset(str, 0, 512);
	strncpy(str, "This is a test.", strlen("This is a test."));
	return str;
}
这种情况下,分配的变量会被存放在文字常量区,不是临时变量
int main(int argc, char **argv)
{
	printf("hello world\n");
	printf("hello world\n");
	printf("hello world\7");	//a short bell
	
	char *s1 = NULL	;
	char *str = NULL;
	get_memory(&str, 10); //for get_memory function
	//
	//str = Get_memory(str,10);
	strcpy(str,"Hello");
	puts(str);
	puts("\n");
	free(str);
	
	s1 = get_str();
	printf("%s\n",s1);
	
	return 0;
}



hello world
hello world
hello worldHello


This is a test.
请按任意键继续. . .

posted @ 2012-07-06 20:48  wdliming  阅读(304)  评论(0编辑  收藏  举报