C++ * un & (pointeru sāga)

Visiem vienmēr šķiet, ka pointeri ir ļoti sarežģīti, bet īstenībā tā nav. Zemāk ar piemēriem izskaidrošu kādēļ visi vienmēr ir baigā starā par pointeriem.

Reference operator &

&
Bildē skaidri redzams, ka andy vērtība ir 25, bet šis te 25 glabājas atmiņas šūnā ar adresi 1776.

Tātad sanāk, ja ted = &andy, tad ted ir vienāds ar andy atmiņas šūnas adresi, respektīvi, ja koda izpildes laikā andy tiek mainīts, tad automātiski tiek mainīts arī ted, jo abi norāda uz vienu un to pašu atmiņas šūnu (or adresi, whatevaa).

Lai nejauktu lietas noskaidrosim kas notiek, ja fred = ted. Šeit vienkārši fred tiek piešķirta tā vērtība, kura pašlaik ir ted, respektīvi, fred norāda uz atmiņas šūnu ar adresi 1776.

Dereference operator *

*
Bildē tiek izskaidrots bob = *ted. Pievienojot zvaigznīti mēs norādam, ka gribam saņemt vērtību uz kuru norāda ted nevis atmiņas šūnas adresi uz kuru norāda ted. Ja zvaigznīte netiktu pievienota tad bob būtu vienāds ar ted, bet ted ir norāde uz atmiņas adresi 1776. Abiem operatoriem ir pilnībā pretējas nozīmes.

Respektīvi:

& ir reference operator un var tikt interpretēts kā “address of”
* ir dereference operator un var tikt intepretēts kā “value of”

Tātad visi zemāk esošie apgalvojumi ir patiesi:

andy == 25
&andy == 1776
ted == 1776
*ted == 25

Programmas piemērs

int main () {
   int firstvalue, secondvalue;
   int * mypointer;

   mypointer = &firstvalue;
   *mypointer = 10;

   mypointer = &secondvalue;
   *mypointer = 20;

   cout << "firstvalue is " << firstvalue << endl;
   cout << "secondvalue is " << secondvalue << endl;

   return 0;
}

Lai arī programmā nekur tieši netiek noteiktas firstvalue vai secondvalue vērtības beigu beigās abi variabļi tomēr satur vērtības pateicoties mypointer.

Advertisement


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.