0

I am having a hard time understanding how exactly are we allowed to play around with strings in c.

At class we were told that: - If we use the definition:

char *str="I love dogs";

we are NOT allowed to change the content of the string, and writing:

str[0]='W' 

will result in an error. - If we use the definition:

char str[N]="I love dogs";

we are allowed to change the content of the string.

Will the functions in , for example strcpy, work in either case? Because I think I have seen an example where it worked.

Can anyone please explain when exactly can I change the content of a string, and why? Because now when I try to work with a string I have no idea what I am allowed to do and what not.

EDIT: Another thing, if we have:

char str[N]="I love dogs";

and we do something like

char *str2=str;

will we be able to change str2?

Thanks a lot.

איתן לוי
  • 433
  • 1
  • 3
  • 9
  • It's very simple: if it's declared `const`, or it's a pointer to a string literal, you aren't allowed to modify it. – Barmar Feb 16 '19 at 01:11
  • It's a historical mistake that string literals aren't automatically declared `const`. They fixed that in C++. – Barmar Feb 16 '19 at 01:13
  • Can you please explain what will happen for the example at then end of my post? Does it count as an array or not? And why? – איתן לוי Feb 16 '19 at 01:43
  • Of course it's an array. `char str[N]` declares an array. – Barmar Feb 16 '19 at 01:43
  • `str2` is a pointer to the array, it doesn't change anything about whether the array is modifiable. – Barmar Feb 16 '19 at 01:44
  • @Barmar "It's a historical mistake that string literals aren't automatically declared const" --> _String literals_ existed years before `const`. Changing the language to "automatically declared const" would have broken much existing code base. Given C is still highly use, the choice is not a _mistake_ - just an unfortunate paradigm we should have evolved out of by now. – chux - Reinstate Monica Feb 16 '19 at 02:42
  • @chux Yes, that's the history I meant -- for backward compatibility we're stuck with this unfortunate inconsistency -- they're not modifiable, but they're not `const`. – Barmar Feb 16 '19 at 02:52

0 Answers0