-4

I'm trying to implement my own strcpy function , here is the code :

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



void Strcat(char *p1,char*p2)
{
    while(*p1!='\0'){p1++;}; //this increments the pointer till the end of the array (it then points to the last element which is '\0')

    while(*p2!='\0'){*p1++=*p2++;};
}
int main()
{
    char txt1[]="hell";
    char txt2[]="o!";

    printf("before :%s\n",txt1);
    Strcat(txt1,txt2);
    printf("after :%s\n",txt1);

}

Everything works fine .

However , when I change

char txt1[]="hell";
char txt2[]="o!";

to

char *txt1="hell";
char *txt2="o!";

I face a Segmentation fault ,

Why is that ?

Aren't they ( both initialization methods) equivalent ?
Aren't "txt1" and "txt2" both act like a pointer to the first element of the char array ?

1 Answers1

0

String literals are not modifiable and trying to modify them invokes undefined behavior.

char txt1[]="hell"; is a character array, so modyfying its contents is allowed.

char *txt1="hell"; is a pointer to a string literal, so you must not modify what is pointed.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70