-1

I am a beginner programmer. I wrote the following code to copy the one string into other, using pointers. But I am not getting the output. The compiler says segmentation fault. I have gone over and over the program, but to no avail. I am not able to locate the fault, and how to fix it. It would be hard to believe but I have been stuck for almost 2 hours now. Any help is greatly appreciated.

#include<stdio.h>

char *copy(char*, char*);

int main() {
    char *str1 = "avanti";
    char *str2 = "ujj";

    printf("%s\n", str1);

    char *result = copy(str1, str2);

    printf("%s", result);
}

char *copy(char *str1, char *str2){
    int i=0;
    while (*(str2+i) != '\0') {
        *(str1+i) = *(str2+i);
        i++;
    }

    *(str1+i) = '\0';
    return str1;
}
hnefatl
  • 5,860
  • 2
  • 27
  • 49
  • 1
    *Especially* when making your first steps, use `const` liberally. And *please* give your parameters speaking names. `src` and `dest` beat `str1` and `str2` any time. – DevSolar Apr 11 '18 at 15:12
  • 1
    Note that using `char str1[] = "avanti";` would be OK because it is longer than what you copy into it. If you had `char *str2 = "alphabet";`, you would have problems even with the array — a buffer overflow. Also, using `str2[i] != '\0'` is a lot easier to read than `*(str2 + i) != '\0'` — and there is no difference in efficiency between the two. – Jonathan Leffler Apr 11 '18 at 15:13
  • @JonathanLeffler Re your second point, the question looks like an exercise in understanding syntax, so using `*`s exclusively seems reasonable and not deserving of criticism per se, although the array syntax is great additional info – user234461 Apr 11 '18 at 15:17

1 Answers1

0

"avanti" is a string constant, not a place you can copy to. You might change it to char str1[] = "avanti"; This is an array of characters that is initialized with the value of the string constant "avanti"

cleblanc
  • 3,678
  • 1
  • 13
  • 16