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 ?