简体   繁体   中英

Use of strcpy() in pointers to string in C

I'm trying to use strcpy() with pointers to strings and after a successful compilation when I run it it gives error. I don't know why this is happening.

int main()
    {
         char *s1="abcd";
         char *s2="efgh";

         strcpy(s2,s1);

         printf("%s\n", s1);
         printf("%s\n",s2);

         getch();
    }

These are string literals, you can't modify them because they're stored in read-only memory.

If you want to change this so you can modify them, use char s[] . This will store the strings on the stack:

         char s1[] = "abcd";
         char s2[] = "efgh";

If you want pointers to these, simply create pointers:

         char *p1 = s1;
         char *p2 = s2;

or you can create them with compound literals from C99:

         char *p1 = (char []){"abcd"};
         char *p2 = (char []){"efgh"};

A full program that puts the strings on the stack:

int main(void)
{
     char s1[] = "abcd";
     char s2[] = "efgh";

     strcpy(s2, s1);

     printf("%s\n", s1);
     printf("%s\n", s2);

     getchar();
}

Output:

 abcd abcd

You are trying to copy all content from first pointer string to second pointer string then I like to suggest you to use malloc

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char** argv) {

      char *s1 ="abcd";
      char *s2 ="efgh";

      s2 = (char *) malloc(1 + strlen(s1));

      strcpy(s2, s1);

      printf("%s\n", s1);
      printf("%s\n", s2);

      return 0;
}
output -:abcd                                                                                                                
         abcd 

hope this will fulfill your question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM