harpribot
harpribot

Reputation: 223

const char* still modifies the pointed value

Why is the value pointed by a const char* being updated by a char array that should just hold a copy of the original string literal that should be stored in the ROM.

I know the basic theory of const char*, char* const, const char* const from this link const char * const versus const char *?

#include <stdio.h>
#include <stdlib.h>

int main(){

    char a[] = "ABCD";
    char z[] = "WXYZ";
    const char* b = a;
    a[1] = 'N';  // WHY THIS WORKS AND UPDATES THE VALUE IN B.... a should make its own copy of ABCD and update
                 // it to NBCD... b should still point to a read only memory ABCD which can't be changed4

    //b[1] = 'N'; // THIS FAILS AS DESIRED
    printf("%s\n", b);   // Output -> ANCD

    return 0;
}

Upvotes: 0

Views: 109

Answers (4)

this
this

Reputation: 5290

C only prohibits modifying an object defined with the const specifier. Your object a was not defined with that specifier, therefore it can be modified.

While it is true that it cannot be modified through b, it can be modified through other means.(like a).

Upvotes: 0

CiaPan
CiaPan

Reputation: 9571

You made b a pointer-to-const, so you can not modify values pointed at by b using b[...]. However you did not make a a const-pointer and you can modify the a[] contents.

Variable b keeps what you have assigned. And you assigned a pointer to the first item of a array. Now b points at the same memory location where a[0] is stored. Once you modified a array contents, you see that b points at the same location, containing modified data now.

Upvotes: 0

Steephen
Steephen

Reputation: 15824

What you are missing to understand is what is a simple pointer. When you write

const char* b = a;

It says variable b points to same memory location of variable a. So whatever change you make in a will reflect in memory pointed by b too.

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122373

const char* b = a;

const here means you can't modify what the pointer points through b, that's it. It's still legal to modify the content through a.

Upvotes: 4

Related Questions