Question

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.

Was it helpful?

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.

OTHER TIPS

An important thing to notice: strcpy's behavior is undefined (see C99 7.23.2.3:2) when provided with overlapping source and destination. So what you're doing, no matter how the output looks, is basically not guaranteed to work unless your C implementation's documentation states otherwise.

Use memmove when moving data within a string.

You should also be very careful in how you declare your string. The code you provided is correct:

char string[] = "foo";

The string is an array of characters, initialized to contain four elements: 'f', 'o', 'o', '\0'.

But, very similar code would be incorrect:

char * string = "foo";

What this code does is initializes a char pointer to the address of a constant string literal "foo". A correct version would be:

const char * string = "foo";

If you tried to modify such a string, the compiler would rightly complain.

strcpy is (Dest, Src). Your source starts at position 1 and goes to the end of the string. It copies the string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).

Maybe something like this will work:

char *strcpy(char *dest, const char *src)
{
   char *save = dest;
   while( (*dest++ = *src++) )
   return save;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top