0

I am trying to pass pointers to strcpy() function. But on running this code, I get no output and the program stops responding, even though I don't get any compile error. I know that strcpy() function takes the arguments as pointers, and here I am passing the pointers directly. So I want to know why the following code is not working properly. And also tell me how to modify the code and if possible using same concept, i.e. by passing pointers to strcpy() function

# include<stdio.h>
# include<conio.h>
# include<stdlib.h>
# include<string.h>
int main() {
    char *rt = "dart";
    char *ft = "gart";
    strcpy(rt, ft);
    printf("%s", rt);
    system("PAUSE");
}
  • 6
    You cannot copy to a read-only string literal. Please try with `char rt[] = "dart";`. Then when you pass `rt` to `strcpy` the array decays to a pointer. – Weather Vane Jan 28 '17 at 18:34
  • @WeatherVane: Just to add that any string longer than the initialiser will also cause trouble, aka _undefined behaviour_. – too honest for this site Jan 28 '17 at 18:40
  • 1
    Read the difference between char array and string literal here http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c – Karthick Jan 28 '17 at 18:43
  • 2
    Because your `printf()` does not include a newline (`\n`), typical C library implementations *cache* the output. If you want to ensure the output is actually *flushed*, visible to the user, add `fflush(stdout)` in the appropriate place. – Nominal Animal Jan 28 '17 at 18:43

1 Answers1

0

First of all you need a placeholder to store your to be copied source string using strcpy(). You need to declare a char array[] where you will copy the source string.

int main() {
    char rt[10];
    char *ft = "gart";
    strcpy(rt, ft);
    printf("%s", rt);
    return 0;
}

Also make sure destination array 'rt' in this case has sufficient memory to store the to be copied string. Otherwise avoid using strcpy() and you should use strlcpy().

user7375520
  • 273
  • 2
  • 15