Using Integer And Char Pointers in C++ or C? -


int *ab = (int *)5656; cout << *ab; //here appcrash.   int *ab; *ab = 5656; cout << *ab; //these block crashes app too. 

but can hex value of content of pointer if write this:

int *ab = (int *)5656; cout << ab; //output hex value of 5656. 

so want ask: * operator brings contents of pointer(?) why in this(these) example(s) app crashes?

and can use operator if change code this:

int = 5656; int *aptr = &a; cout << *aptr; //no crash.  

and why dereference operator(*) brings first character of char:

char *cptr = "this test"; cout << *cptr; // here output = 't' cout << cptr; // here output = 'this test' 

int *ab = (int *)5656; cout << *ab; //here appcrash. 

in case, setting pointer ab point @ address 5656. know what's @ address? no don't. telling compiler trust there int there. then, when dereference pointer *ab, find there isn't int there , undefined behaviour. in case, program crashes.

int *ab; *ab = 5656; cout << *ab; 

in case, have uninitialised pointer ab dereference assign 5656 int points at. since it's uninitialised, dereferencing gives undefined behaviour. think of way. haven't put addres in ab don't know points. can't dereference , hope points @ int.

int = 5656; int *aptr = &a; cout << *aptr; 

this fine because know have int object value 5656 , know aptr contains address of int object. it's fine dereference aptr.

const char *cptr = "this test"; cout << *cptr; // here output = 't' cout << cptr; 

(your code using deprecated conversion char*, changed const char*.)

the string literal "this test" gives array containing const chars. however, undergoes array-to-pointer conversion giving pointer first element. since each element const char, pointer const char*. store pointer in cptr.

so cptr points @ first element of string. dereferencing pointer gives first element, first character of string. output t.

the i/o library has special overloads take const char*s , treat pointing string of characters. if didn't, cout << cptr print out address in cptr. instead, these special overloads print out null-terminated array of characters cptr assumed point to.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -