0

I was asked in an interview.how can we change the values of character array and a pointer to a string.

Here is my Code snippet.

        #include<string.h>
        int main()
        {
        char ch[]="abc";
        char *ptr="xyz";
        ptr="xyz";

        //strcpy(ptr,"xyz") is giving segmentation fault
       //ch="ABC"; //  is throwing error: incompatible types in assignment

       strcpy(ch,"ABC");
       return 0;
       }

Could some one please explain how ptr="xyz" is working when ch="ABC" is throwing an error and strcpy(ptr,"xyz") is giving segmentation fault and strcpy(ch,"ABC") is working fine.

knp
  • 89
  • 1
  • 6

1 Answers1

-1

In C you can not directly equate character array and a constant string hence you are getting error at

ch = "ABC"

you need strcpy for this purpose!

While doing

strcpy(ptr, "XYX")

ptr is not allocated any memory yet so it gives segmentation fault!

Nullpointer
  • 1,086
  • 7
  • 20