c++ - Changing constant pointer's address -


i'm trying understand 1 thing.

i know can't change constant pointer's value, can change address, if initialize pointer following way:

int foo = 3; const int *ptr = &foo; *ptr = 6; // throws error int bar = 0; ptr = &bar; // foo == 0 

now, let's declare (/define, never remember one) function:

void change(const int arr[], int size);  int main() {    int foo[2] = {};    change(foo, 2);    std::cout << foo[0]; }  void change(const int arr[], int size) {    // arr[0] = 5 - throws error    int bar = 5;    arr = &bar; } 

the last line in code above doesn't throw errors. however, when function on , display first element, shows 0 - nothing has changed.

why so?

in both situations have constant pointers, , try change address. in first example works. in second 1 doesn't.


i have question. i've been told if want pass two-pointers type function, const keyword won't work expected. true? , if so, what's reason?

you're screwing terminology lot, i'm going start there because think major cause of confusion. consider:

int x; int* p = &x; 

x int , p "pointer int". modify value of p means change p point somewhere else. pointers value address holds. pointer p holds address of int object. change pointer's value doesn't mean change int object. example, p = 0; modifying p's value.

in addition that, address of p not address holds. address of p if did &p , of type "pointer pointer int". is, address of p find pointer p in memory. since object doesn't move around in memory, there's no such thing "changing address".

so that's out of way, let's understand constant pointer is. const int* not constant pointer. it's pointer constant object. object points constant, not pointer itself. constant pointer type more int* const. here const applies pointer, of type "const pointer int".

okay, i'll give easy way remember difference between declaration , definition. if bought dictionary , had list of words in it, call dictionary? no, dictionary supposed filled definitions of words. should tell words mean. dictionary no definition declaring such words exist in given language. declaration says exists, , definition gives meaning of it. in case:

// declaration void change(const int arr[], int size);  // definition void change(const int arr[], int size) {    // arr[0] = 5 - throws error    int bar = 5;    arr = &bar; } 

now explain issue here. there's no such thing array argument type. array type argument converted pointer. declaration of change identical to:

void change(const int arr*, int size); 

when arr = &bar; assigning address of bar pointer arr. has no effect on array elements arr pointing to. why should it? changing arr points to, not objects points at. , in fact can't change objects points @ because const ints.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -