c++ - Changing the address a pointer is pointing to -


i want change different pointer (different types), point null/0/nullptr..., have use variable this!
understand pointers , know problem is, don't know how solve it.

so need

int nullpointer = nullptr;                 // data type can change if needed int* myintpointer = nullpointer; float* myfloatpointer = nullpointer; foo* myfoopointer = nullpointer; 

as shown above, not possible because of invalid conversion error (int int*/float*/foo*).

so how can archiv this? requested more complex example clarification:

class foo {     float floatvar; };  class bar {     char charvar; };  void changesomething(bar* pbartmp) {     /* pglobal member of class , type depends on method */     pglobal = pbartmp; }  int main() {     /* working fine */     int var = 1;     int *pointer  = &var;      /* working fine */     foo *pointer = 0;    //nullptr or null or __null (compiler dependend)      /* not working because newaddress int , not bar* / foo* / int* */     int newaddress = 0;      // 1 of following present, depends on      // method/class (just visualization)      bar *pointer = newaddress;                    foo *pointer = newaddress;     int *pointer = newaddress;      changesomething (pointer); } 

i not allowed change int newaddress; int* newaddress;.
overall won't use else null / 0 / nullptr / ...

another difficulty is, cannot use reinterpret_cast cause of coding guidelines.

int* p3 = 1; //error invalid conversion int int

you can directly set address of pointer in c++

int* p3 = reinterpret_cast<int*>( 0x00000001 ); 

but not idea since dont know pointer points in memory , de-referencing lead undefined behavior.

its invalid conversion because 1 has type int , it's not possible assign pointer variable int * without cast.


int* p2 = 0; //p null-pointer

pointers pointing null should initialized

int* p2 = nullptr; 

instead of

int* p2 = 0; 

since c++11 can create instance of std::nullptr_t , assign pointers.

std::nullptr_t initaddr; int* p2 = initaddr; 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -