Home > database >  I'm confused about a topic about fixed variables
I'm confused about a topic about fixed variables

Time:03-06

I have defined a list pointer to type const, but then I changed the value of one of the arguments in the list, but the compiler did not get an error from me and changed the value to a new value. At first I suspected that maybe after changing the value of the pointer address changes and the pointer is pointing to a new list, but I got the pointer address after and before changing the argument and it was one. Now I want to know how a list of type can change its value?

int main()
{
    
    const int k = 5;
    const char *list[k] =
                {
                "computer",
                "physics",
                "mathematics",
                "text",
                "book"
                };
    
    const char** p = list;
    cout << "before: " << (list   4);
    list[3] = "arabi";
    //cout << "\n" << setfill('-') << setw(10) ;
    cout << "\nafter: " << list   4;
    cout << "\n";
    for (int i = 0; i < k; i  )
    {
        cout << list[i] << endl;
    }
    char* ch = (char *)"plus";
    
}

[run][2]

CodePudding user response:

const char *arr[n] is an array, which stores elements of type const char *.

cost char * is a pointer to (multiple) const chars, which cannot be modified.

Note, that the things that cannot be modified are the chars that are pointed to by the const char *. The const char * pointers themselves can be modified!

When you do arr[3] = "arabi", you are not changing the value of the string pointed to by arr[3](which you couldn't, as it is const), but you are changing the pointer itself(which is not const)!

CodePudding user response:

const can be used in 2 ways when declaring a pointer:

// The value is modifiable, 
// The location where the pointer is pointing cannot be changed
const type* name; 

..and:

// The value is not modifiable, 
// The location where the pointer is pointing can be changed
type* const name;

They can also be used in combination:

// The value is not modifiable, 
// The location where the pointer is pointing cannot be changed
const type* const name;

In your case, you are using the first one, so the values can be changed.

If you want the values to not be changed, you'll have to use:

const char* const list[k] =
{
    "computer",
    "physics",
    "mathematics",
    "text",
    "book"
};
  • Related