2

Why does this work:

char foo[6] = "shock";`

while this does not work:

char* bar = "shock"; //error

Why does bar have to be const while foo doesn't? Arrays in C decay to pointers, so don't foo and bar technically have the same types?

6
  • 1
    They are not the same type. foo is type array of char while baris type pointer to char.
    – Galik
    Commented Dec 4, 2022 at 23:48
  • @beangod - i compiled c by mistake. my bad,see answer below
    – pm100
    Commented Dec 4, 2022 at 23:49
  • 1
    foo is a copy of the const "shock". bar is a pointer to the const "shock". You can decide whether the copy will be const or not. Commented Dec 4, 2022 at 23:50
  • Also, you may absolutely "have a non-const char* in C++". It simply can't point to something that is const. Commented Dec 4, 2022 at 23:53
  • 2
    Do not tag C for C++ questions. Commented Dec 5, 2022 at 0:03

4 Answers 4

7

With this declaration:

char foo[6] = "shock";

Variable foo is type array of char and it containes 6 non-const chars. The string literal contains const chars which are copied into the array on initialization.

While with this declaration:

char* bar = "shock"; //error

Variable bar is type pointer to char. You are trying to make it point to the address of "shock" which is a string literal containing const char.

You can't point a pointer to non-const char at a const char.

So you must do this:

const char* bar = "shock";`
7

Literals are held in reserved areas of memory that are not supposed to be changed by code. Changing the value held at the address storing that literal would mean that every time any other code tried to use that literal, it would find the wrong value in that memory. So it is illegal to modify that memory, and hence illegal to treat it as not constant.

Source

1
  • Very often, it is in read-only blocks of memory so cannot be changed.
    – doron
    Commented Dec 4, 2022 at 23:54
3

because "shock" is a constant, so a pointer to it must be const

for historical reasons C allows this (and causes many errors that lead to SO posts)

1
char* bar = "shock";

is roughly equivalent to

const char anonymousArray[6] = "shock";
char *bar = anonymousArray;

Arrays decays to pointers. That's not the same as actually being pointers.

Not the answer you're looking for? Browse other questions tagged or ask your own question.