C++ Memcpy字符指针
我有一个简单的程序,其中我想使用memcpy连接两个char指针,但我在memcpy行上获得了访问冲突读取位置C++ Memcpy字符指针,c++,c,pointers,char,memcpy,C++,C,Pointers,Char,Memcpy,我有一个简单的程序,其中我想使用memcpy连接两个char指针,但我在memcpy行上获得了访问冲突读取位置 char *first = new char[10], *second=new char[10]; first="Hello "; printf("\second: "); scanf("%s",&second); memcpy(first,second,strlen(second)+1); printf ("Result: %s\n", first); 因为复制到常量中会
char *first = new char[10], *second=new char[10];
first="Hello ";
printf("\second: ");
scanf("%s",&second);
memcpy(first,second,strlen(second)+1);
printf ("Result: %s\n", first);
因为复制到常量中会导致违反,所以我尝试了以下方法:
char *first = new char[20], *second="world!";
printf("first: ");
scanf("%s",&first);
memcpy(first,second,strlen(second)+1);
printf ("Result: %s\n", first);
这样我就可以访问写入位置。如何正确连接这两个指针?您的
memcpy
相当于memcpy(“Hello”,second,strlen(second)+1)代码>。复制到常数(在某些平台上,显然包括您的平台)是一种访问冲突
char *first = new char[10], *second=new char[10];
first="Hello ";
首先,将First
指向您分配的一些内存。然后扔掉指针,让它指向一个静态字符串。你不是这个意思。也许你的意思是:
strcpy (first, "Hello ");
这会将常量的数据复制到第一个指向的空间中。更改
scanf("%s", &first);
到
扫描时访问了错误的内存。char*concat(const char*first,const char*second)
char * concat(const char * first, const char * second)
{
int lf = strlen(first);
int ls = strlen(second);
int len = lf + ls;
char * rb = new char[len+1];//You need this +1 here
memcpy(rb, first, lf);
memcpy(rb+lf, second, ls);
rb[len] = 0;
return rb;
}
int main ()
{
char *first = new char[10], *second=new char[10];
strcpy(first, "first");//This is an unsafe way. You can take the value from anywhere possible
strcpy(second, "second");//This is an unsafe way. You can take the value from anywhere possible
char * third = concat(first, second);
cout << third << endl;//Don't use cout << concat(first, second) << endl; since it leads to a emory leak
delete [] third;
return 0;
}
{
int lf=strlen(第一);
int ls=strlen(秒);
int len=lf+ls;
char*rb=new char[len+1];//这里需要这个+1
memcpy(rb,first,lf);
memcpy(rb+lf,第二,ls);
rb[len]=0;
返回rb;
}
int main()
{
char*first=新字符[10],*second=新字符[10];
strcpy(first,“first”);//这是一种不安全的方法。您可以从任何可能的地方获取值
strcpy(second,“second”);//这是一种不安全的方法。您可以从任何可能的地方获取值
char*third=concat(第一,第二);
CUT首先指向只读存储器。为什么在C++代码中使用<代码> SCAFF < /C>和<代码> Prtff<代码>?YEP。<代码> SCANF函数需要您读取的地址,而不是保存该地址的变量的地址。
char * concat(const char * first, const char * second)
{
int lf = strlen(first);
int ls = strlen(second);
int len = lf + ls;
char * rb = new char[len+1];//You need this +1 here
memcpy(rb, first, lf);
memcpy(rb+lf, second, ls);
rb[len] = 0;
return rb;
}
int main ()
{
char *first = new char[10], *second=new char[10];
strcpy(first, "first");//This is an unsafe way. You can take the value from anywhere possible
strcpy(second, "second");//This is an unsafe way. You can take the value from anywhere possible
char * third = concat(first, second);
cout << third << endl;//Don't use cout << concat(first, second) << endl; since it leads to a emory leak
delete [] third;
return 0;
}