Memcpy Char指针

时间:2014-06-22 08:14:00

标签: 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[20], *second="world!"; 
printf("first: ");
scanf("%s",&first);
memcpy(first,second,strlen(second)+1);
printf ("Result: %s\n", first);

它让我访问违规写入位置。我应该如何正确地连接两个指针?

3 个答案:

答案 0 :(得分:8)

您的memcpy相当于memcpy ("Hello ", second, strlen(second)+1);。复制到常量是(在某些平台上,显然包括你的)访问冲突。

    char *first = new char[10], *second=new char[10]; 
    first="Hello ";

首先,让first指向您分配的内存。然后你把指针扔掉,让它指向一个静态字符串。那不是你的意思。也许你的意思是:

    strcpy (first, "Hello ");

这会将常量数据复制到空格first指向。

答案 1 :(得分:3)

更改

scanf("%s", &first);

scanf("%s", first);

扫描时访问错误的内存。

答案 2 :(得分:3)

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;
}

你不能在不使用额外内存的情况下连接两个字符串,因为每次你需要一个大小为两个给定字符串+1(或更多)的内存块。