0

I am trying to assign a single inside char *ptr and then print the changed value. But it is giving segmentation fault. But don't see the issue if the same is declared as ptr[32] instead of *ptr;

int main () {
    char *ptr = "abcdefghijklm";
    ptr[2] = "q";
    printf("%s",ptr);
}

Any guess what is going wrong here?

273K
  • 29,503
  • 10
  • 41
  • 64
  • Basically you need to study arrays, then pointers, then strings, in that order. `ptr[2] = "q"` is also invalid syntax. – Lundin Oct 19 '21 at 13:47
  • Are you asking for C or C++? In both languages this code is broken, but for different reasons. And each language has its own different solution. – François Andrieux Oct 19 '21 at 13:51
  • Since you tagged as C++, prefer to use `std::string` instead of character arrays. Character arrays can underflow, or overflow and may need to be reallocated. All this is taken care of for you with the `std::string` class. The C language doesn't have `std::string`. – Thomas Matthews Oct 19 '21 at 15:41
  • Since you are modifying the data, you should make the declaration `char ptr[] = /*...*/;` This will allow you to change the contents of the `ptr` array. – Thomas Matthews Oct 19 '21 at 15:43

0 Answers0