首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

用malloc分配内存后,用memcpy将字符串复制进去解决思路

2013-10-21 
用malloc分配内存后,用memcpy将字符串复制进去如题,用malloc 分配内存后,用memcpy 将字符串复制进去。若用

用malloc分配内存后,用memcpy将字符串复制进去
如题,用malloc 分配内存后,用memcpy 将字符串复制进去。若用字符数组指明长度就不会错。而用malloc则提示“Segmentation Fault - core dumped”(在ubuntu中运行)

#include"memory.h"
#include"stdio.h"
#include"string.h"

char d[30];
memcpy(d,s,sizeof(s)+1);
sprintf("%s",d);

return 0;
}*/

int main()
{char *s="asdgsadggh";
//char d[30]; 用字符数组就不会错
char *d=(char*)malloc(sizeof(char)*(1+strlen(s)));
memcpy(d,s,strlen(s)+1);
printf("%s",d);
return 0;

}

请高手指点!谢谢!

[解决办法]

探讨
如题,用malloc 分配内存后,用memcpy 将字符串复制进去。若用字符数组指明长度就不会错。而用malloc则提示“Segmentation Fault - core dumped”(在ubuntu中运行)

#include"memory.h"
#include"stdio.h"
#include"string.h"

char d[30];
memcpy(d……

[解决办法]
只需要#include"stdlib.h"即可,另外这里最好用strcpy(d,s):
C/C++ code
#include"memory.h"#include"stdio.h"#include"string.h"#include"stdlib.h"int main(){char *s="asdgsadggh";char *d=(char*)malloc(sizeof(char)*(1+strlen(s)));memcpy(d,s,strlen(s)+1);//strcpy(d,s);printf("%s\n",d);return 0;} 

热点排行