lostdong12
lostdong12

Reputation: 97

printing C string after 0 terminating it

int main(void) {
   // your code goes here
   char* qwe = "qwe";
   qwe[2] = '\0';
   printf("%s\n", qwe);
   return 0;
}

I been messing with C pointers to see if I understand them correctly. From the code, qwe contains char pointers to letter 'q', and can reach to 'w', 'e', and '\0'. qwe[2] = *(qwe + 2), which is e. I terminated it with '\0'. Now it is giving me a segmentation fault when I try to print it. I was expecting the output qw.

Upvotes: 0

Views: 77

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

You get segmentation fault not because of printing, but because you try to make a write into memory of a string literal. If you make a copy into writable memory, your code would work:

int main(void) {
   char qwe[] = "qwe";
   //   ^^^^^
   qwe[2] = '\0';
   printf("%s\n", qwe); // prints "qw"
   return 0;
}

Upvotes: 3

Related Questions