-1

Can someone explain why

 char *s1 = "abcd";
 char *s2 = s1;
 s1[0] = "z";
 s1[2] = "\0";

gives me a bus error 10 BUT

 char s1[] = "abcd";
 char *s2 = s1;
 s1[0] = "z";
 s1[2] = "\0";

doesn't?

are char *s1 and char s1[] not equivalent? Please explain, thanks.

Elbert
  • 31
  • 2
  • "_are char *s1 and char s1[] not equivalent?_" -- No. Array != Pointer. You got that error because you aren't supposed to change a string literal and doing so results in Undefined Behavior. – Spikatrix Sep 19 '15 at 06:06
  • And Now that I take a closer look at what you are doing, it makes no sense. You are trying to store a string (`char*`) in a `char` variable. Keep in mind that `"..."` is a string while `'.'` is a character. – Spikatrix Sep 19 '15 at 06:09

2 Answers2

1

Be free (of historical lazyness), be wise! Pointers are not arrays! Tutorials have lied you!

In the first example, you're modifying a pointer to a constant string literal, and that's undefined behaviour. Anything can happen then!

Meanwhile, in the second case, the string itself is stored inside the array, and the array itself is in the stack. Thus, the second example exposes more than a plain innocent array that's modifiable.

The s2 pointers make no difference in all this. IMHO, the fact that the first case is compilable is just historical lazyness, otherwise known as backwards compatibility.

BTW: Are you assigning string literals to chars? That's undefined behaviour too!

3442
  • 8,248
  • 2
  • 19
  • 41
0

In the first case you set a s1 pointer to the address const string. Const string are stored in read -only area and you cannot modify it. This means that you cannot modify a character s[x]. It is UB

In the second case you declare a local array inited with a string. In this case only the init value is read-only and after init you use an allocated array that can be modified.

LPs
  • 16,045
  • 8
  • 30
  • 61