zoukankan      html  css  js  c++  java
  • 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.
    请按任意键继续. . .

  • 相关阅读:
    FZU 2112 并查集、欧拉通路
    HDU 5686 斐波那契数列、Java求大数
    Codeforces 675C Money Transfers 思维题
    HDU 5687 字典树插入查找删除
    HDU 1532 最大流模板题
    HDU 5384 字典树、AC自动机
    山科第三届校赛总结
    HDU 2222 AC自动机模板题
    HDU 3911 线段树区间合并、异或取反操作
    CodeForces 615B Longtail Hedgehog
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/12007682.html
Copyright © 2011-2022 走看看