大家好,关于malloc的问题
- C/C++ code
void getmemory(char *p){ p=(char *)malloc(sizeof(char)*10); }void main(){ char *str=NULL; getmemory(str); strcpy(str,"hello world!"); printf(str);}
这个错误,是因为调用getmemory时,是p申请成功了内存,而str没申请成功吗?如果是那样的话,该怎么传str使得str能申请到内存呢(我不想直接用char *str=(char *)malloc(sizeof(char)*10);)
[解决办法]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getmemory(char *&p)
{
p=(char *)malloc(sizeof(char)*10);
}
int main()
{
char *str=NULL;
getmemory(str);
strcpy(str,"hello world!");
printf("%s\n",str);
return 0;
}
[解决办法]
- C/C++ code
void getmemory(char **p){ *p=(char *)malloc(sizeof(char)*10); }void main(){ char *str=NULL; getmemory(&str); strcpy(str,"hello world!"); printf(str);}
[解决办法]
你申请的那段内存没问题啊,是你的那个printf("%s",str);有问题
[解决办法]
嗯,2楼说的有道理,学习了
[解决办法]
- C/C++ code
//返回char*类型的xsize长度的空间char *getmemory(int xsize){ return (char *)malloc(sizeof(char)*xsize); }void main(){ char *str=NULL; str=getmemory(10);//这样不是更通用了吗?原代码中的错误如楼上已经指出:改变的不是STR的指向,而是修改的现在指向的地址的内容。 strcpy(str,"hello world!"); printf(str);}