Illusionist
Illusionist

Reputation: 5509

array of constant pointers

Ok, I know that this is invalid

 char char_A = 'A';
    const char * myPtr = &char_A;
    *myPtr = 'J'; // error - can't change value of *myP

[Because we declared a pointer to a constant character]

Why is this valid?

 const char  *linuxDistro[6]={ "Debian", "Ubuntu", "OpenSuse", "Fedora", "Linux Mint", "Mandriva"};

for ( int i=0; i < 6; i++) 
cout << *(linuxDistro+i)<< endl;

*linuxDistro="WhyCanIchangeThis";// should result in an error but doesnt ? 
for ( int i=0; i < 6; i++) 
cout << *(linuxDistro+i)<< endl;

Thanks for looking!

Upvotes: 6

Views: 8774

Answers (4)

cnd
cnd

Reputation: 33784

because char is not char[], so when you access to * of char[] you access the first element of it (Debian).

when you shift pointer (e.g. +1 it) you access next element of array

here is good example for better understanding

#include <iostream>
using namespace std;

int main ()
{
  int numbers[5];
  int * p;
  p = numbers;  *p = 10;
  p++;  *p = 20;
  p = &numbers[2];  *p = 30;
  p = numbers + 3;  *p = 40;
  p = numbers;  *(p+4) = 50;
  for (int n=0; n<5; n++)
    cout << numbers[n] << ", ";
  return 0;
}

this will output:

10, 20, 30, 40, 50,

Upvotes: 1

user1797612
user1797612

Reputation: 832

because the pointer is a variable that stores a memory address, if a pointer is const the pointer keeps storing the same memory address, so the value of the pointer itself can't change, but you are saying nothing about the value pointed by the pointer, according to what you have, chaging the pointed value it's an allowed operation.

Upvotes: 1

Matt
Matt

Reputation: 6050

*linuxDistro is still a pointer, it is linuxDistro[0], *linuxDistro="WhyCanIchangeThis" it just change the pointer to point to a new address, not to modify the content in the old address, so it is OK.

If you write **linuxDistro='a', it should error.

Upvotes: 3

user529758
user529758

Reputation:

You write

*linuxDistro =  "WhyCanIchangeThis";

which is perfectly valid, because the declaration of linuxDistro was

const char *linuxDistro[6];

i. e. it's an array of 6 pointers to const char. That is, you can change the pointers themselves, just not the characters pointed to by those pointers. I. e., you can not compile

*linuxDistro[0] = 'B';

to obtain the string "Bebian", becuse the strings contain constant characters...

What you probably want is an array of constant pointers to constant characters:

const char *const linuxDistro[6];

Upvotes: 12

Related Questions