c语言getmemory面试题,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

#include

#include

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. 请按任意键继续. . .

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值