Use the STRCPY C

c, strcpy

Solution

The call `strcpy(&string[0],&string[1]);` means: copy the NULL-terminated string starting at the address of string[1] to the address of string[0]. This means you are copying the string starting at offset 1 (`tackflow`) to the address of offset 0. Or put it another way: you are moving the string one character to the left, overwriting the `s`.

`strcpy` is used to copy an array of bytes that are terminated by a NULL byte (a C string) from one address (the second parameter) to another address (the first parameter). Usually, it is used to copy a string from one memory location to a totally different memory location:

char string[] = "stackflow";
char copied_string[10]; // length of "stackflow" + NULL byte

strcpy(copied_string, string);
puts(copied_string);

As @PascalCuoq correctly points out, your call is undefined behavior, which means anything may happen. The standard says:

If copying takes place between objects that overlap, the behavior is undefined.

So you are lucky you got a "sane" output at all.

Problem

I code: ``` #include<stdio.h> #include<conio.h> #include<string.h> void main() { char string[]="stackflow"; strcpy(&string[0],&string[1]); puts(string); getch(); } ``` The result is "tackflow". I don't understand about it. Who are you can explain? Thank in advance.

Original source

Related problems