Reputation: 23
I wrote this piece of code
int main()
{
char a[] = "ABCD";
const char* b = a;
a[1] = 'E';
printf("%s %s", a, b);
getchar();
}
The code compiled and ran successfully.
How am I able to access the memory pointed by 'const char* b' and modify it ? Does it mean that for a shared memory const definition does not matter ?
Thank you
Upvotes: 1
Views: 191
Reputation: 5372
char * p
p
is a non-constant pointing to a non-constant character. We can change the character value using p
, and change p
to point at another character.
char const * p
const char * p
p
is a non-constant pointer to a constant character. We can't change the character value using p
, but can change p
to point at another character.
char * const p
p
is a constant pointer to a non-constant character. We can change the character value using p
, but can't change p
to point at another character.
char const * const p
const char * const p
p
is a constant pointer to a constant character. We can't change the character value using p
, or change p
to point at another character.
In your question, a
and b
point at the same memory. b
is declared as const char *
, so it is a non-constant pointer to a constant character. That doesn't mean that anybody else can't modify the character. Only that you can't modify the character using b
.
Upvotes: 2
Reputation: 206717
How am I able to access the memory pointed by
'const char* b'
and modify it ?
You are able to access memory pointed to by b
regardless of whether it is declared as
const char* b;
or
char* b;
You won't be able to modify the value through b
. The following is an error:
b[1] = 'E';
Does it mean that for a shared memory const definition does not matter ?
The const
qualifier matters -- whether it is shared memory or not. Had you used:
const char a[] = "ABCD";
const char* b = a;
the following will be an error too.
a[1] = 'E';
Upvotes: 1
Reputation: 3073
const char * b
just means that you cannot modify what b
points to ... through b
. The place it points to is an ordinary memory location, though, and can be modified by anything else that points to it.
The contract represented by const
is only valid with respect to the variable or method the const is attached to.
Upvotes: 1
Reputation: 44268
Declaration of b
with type const char *
means that you cannot modify data using pointer b
itself, it does not affect memory b
points to in any sense.
Upvotes: 2
Reputation: 227558
const char* b
means that you cannot modify the thing b
points to through b
. But you can modify it through some other means, provided the thing isn't const
in the first place*.
Here is a simplified example:
int a = 0;
const int* p = &a;
a = 42; // OK! a is not const.
*p = 43; // ERROR! Cannot modify a through p.
const int b = 0;
p = &b;
b = 43; // ERROR! b is const.
* This holds for C++. The details may be slightly different in C
Upvotes: 6