1

I'm pretty new to C and there is a concept about strings and pointers I have a hard time to understand. here are three ways to declare a string c :

char *str1 = "Hello world";
char str2[12] = "Hello world";
char *str3 = (char*)malloc(12);
 
char *(str+5)='\0'; // failure
char str[5]='\0' ; //successfully done
char str[5]= '\0' ; //successfully done

Let's say want to extract the "Hello" substring from the string. I can easily do that by looping through the string until a whitespace is encountred, right?

But here comes the problem :

As I'm trying to assign '\0' or any other character to str1, a write access violation is thrown.

But If I assign '\0' to both str2 and str3, no exception is thrown and the strings are successfully truncated.

I would like to get a clear explanation about why it's impossible to change string values if it's declared like str1.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
JustCurious
  • 141
  • 2
  • 1
    `str1` is a pointer to a string literal, those cannot be altered. – anastaciu Aug 18 '20 at 12:10
  • 1
    The three lines with `str` are definitions which cannot be in one code. Also the first one is an incorrect definition. Please make a [mre]. – Yunnosch Aug 18 '20 at 12:12
  • You should not assign `'\0'` to `str2` but `NULL`. – Jabberwocky Aug 18 '20 at 12:13
  • To make the shown code meaningful I propose to insert a line `char str[12];` (or any definition of `str` you would like to discuss) inside the gap and remove all occurences of `char` after that line. – Yunnosch Aug 18 '20 at 12:14
  • Another dupe: [String literals: pointer vs. char array](https://stackoverflow.com/questions/12795850/string-literals-pointer-vs-char-array) – anastaciu Aug 18 '20 at 12:15
  • You make `str1` point to a constant. Then you try to modify the thing `str1` points to. So you are trying to modify a constant. – David Schwartz Aug 18 '20 at 12:17

0 Answers0