0

Having this:

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

int main (void) {

   char *str = "foo\n"; //if 'char str[] = "foo\n";' no problem
   char *c = strchr(str, '\n');
   *c='\0'; //causes "command terminated"
   // *(c+0)='c'    does not help

   return 0;
}

I have no idea, why program crash, when I got c pointer from strchr and then dereference it in assignment.

autistic456
  • 183
  • 1
  • 10
  • you try to modify the literal string`"foo\n"` which is read only. replace `char *str = "foo\n";` by `char str[] = "foo\n";` – bruno May 11 '20 at 15:27
  • I don't understand. I have not added `const` modifier to var `str` to be read-only. Why can I then modify it, when is used array instead of pointer (as in comments of code)? – autistic456 May 11 '20 at 15:29
  • yes but a literal string is readonly anyway – bruno May 11 '20 at 15:29
  • `char str[] foo`, is also literal string, and yet can modify – autistic456 May 11 '20 at 15:30
  • no, a literal string is `"..."`, but having `char str[] = "foo\n";` *str* is not a literal string, it is just initialized using a form with a literal string – bruno May 11 '20 at 15:31
  • if you try to modify an element declared `const` or directely a literal you have an error at *compile time*, if you try to modify a read-only element while you was able to compile you have an error at the *execution time*. In C is is possible to write `char * p = "aze";` but that changes nothing on the fact *p* point to a read only string. Anyway it is better to use `const char * p = "aze";` for the clarity of the source – bruno May 11 '20 at 15:35

0 Answers0