-2

if I have the function scopy that copies a C String from src to dest

char * scopy(char *dest, char *src) {
    char* r = dest;
    while (*src != '\0') {
        *dest = *src;
        dest++;
        src++;
    }
    *dest = *src;
    return r;
}

Why does this function work when called on 2 String initialized like this char a[6] = "abbbb" and char b[4] = "dcd" but doesn't work on Strings initialized like this char * a = "abbbb" and char * b = "dcd"

Karim El Sheikh
  • 339
  • 1
  • 2
  • 11
  • arrays and pointers are different beasts. You might like to read the [c-faq](http://c-faq.com/), especially sections 4, 5, and 6. – pmg May 10 '14 at 21:17

3 Answers3

1

This function invokes undefined behavior when used like that because it tries to modify a string literal, so you can't say it works in either case.

The fact that it appears to work on the char[] is a coincidence -- an unfortunate one, because it gives the wrong impression.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
1

In the code below, variable ptr is pointing to a read-only memory section, which contains "xyz\0". You can change the variable itself, but you can't change the contents of the memory it is pointing to...

char* ptr = "xyz";

In the code below, variable arr is pointing to a read/write memory section, which contains "xyz\0". You can't change the variable itself, but you can change the contents of the memory it is pointing to...

char arr[] = "xyz";

The above should help you to understand why you are getting a segmentation fault in the first case...

Having said that, you have yet another problem in your code - if the string pointed by src is longer than the string pointed by dest, then *dest = *src will most likely cause a segmentation fault:

while (*src != '\0')
{
    *dest = *src;
    dest++;
    src++;
}
barak manos
  • 29,648
  • 10
  • 62
  • 114
0

char*a = "abbbb" is called a string literal, which iirc behaves differently than a char[] in c. Specifically, I do not believe you can modify the individual characters for a string literal.

Try looking here for more information between the two constructors

Community
  • 1
  • 1
Joshua Zollinger
  • 757
  • 1
  • 8
  • 17