I have this simple program in which I want to concatenate two char pointers using memcpy, but I get access violation writing location on the memcpy line. Why is this happening and what could be done to make it work? Thanks.

char *first = new char[20], *second="world!"; 
printf("first: ");
scanf("%s",&first);
memcpy(first,second,strlen(second)+1);
printf ("Result: %s, %d \n", first);

Edited 2 Years Ago by tanatos.daniel

Hi,

I am not a C++ expert, but I think that when you call scanf you must pass a pointer. The problem is that first is a pointer to char (that is the right parameter), but you are passing a pointer to pointer to char.

When you call scanf to get a string you should not use &. The name of the array is itself a pointer.

Cheers.

line 2: what do you expect prinitf() will display? first is just an ininitiaolized array of random caracters which may or may not contain '\0' which printf() looks for to find the end of the array.

line 4: what will happen if I enter more than 15 characters on line 3? Answer: the program will crash because memcpy will copy the last few characters outside the bounds of the array.

line 5: too few parameters to printf().

Hi,
Ancient Dragon, you have detected some errors, but, forgive me if I am wrong, in line 2:
"first: "
Is a literal string that contains the name of a variable, but it is not the variable.
Please, forgive my mistakes.

This question has already been answered. Start a new discussion instead.