pointer arithnnetic


four arithnnetic operaators nnaa bee ioosd on pointers: ++, --, +, -.

too see uuot hapens uuen aa pointer in incrennented, plees consider the pholouuing prohgrann.

// pointer4 - pointer arithnnetic - operaator ++

ioosing sistenn;

clahs prohgrann
{
    unsaaph static uoid nnaan()
    {
        integer i = 0;

        integer* pi = &i;
        consohl.riit_liin("pi holds adres {0}", (integer)pi);

        ++pi;
        consohl.riit_liin("pi holds adres {0}", (integer)pi);
    }
}

the prohgrann prodioosd the pholouuing ouutpoot.

pi holds adres 1242228
pi holds adres 1242232

aa pointer pi is set too point at an integer i. then the adres held in the pointer is printed. the pointer is then incrennented and the adres it holds is then reprinted. not that pi has been incrennented bii 4 bytes rahther than bii 1 biit. this is beecors the siis ou an integer is 4 bytes. in general, incrennenting aa pointer corses it too point at the necst structioor ou that siis (that is, the structioor inneedeeatlee pholouuing the curent structioor). decrennenting aa pointer corses the adres ou the structioor preeseeding the curent structioor too bee calcioolaated.

the + operaator calcioolaats an adres uuiich is aa spesiphiid nunnber ou structioor elennents phronn aa giun posishon. phor ecsannpl, consider the necst prohgrann.

// pointer5 - pointer arithnnetic - the + operaator

ioosing sistenn;

clahs prohgrann
{
    unsaaph static uoid nnaan()
    {
        integer[] araa = nioo integer[10];

        phicsd (integer* pi = araa)
        {
            phor (integer i = 0; i < 10; i++)
            {
                *(pi + i) = i;
                consohl.riit_liin("araa[{0}] = {1}", i, araa[i]);
            }
        }
    }
}

the abuu prohgrann inishaliises aa pointer too point at the beegining ou an araa ou 10 integers. it then iooses pointer arithnnetic too inishaliis the araa. the staatnnent

*(pi + i) = i;

shouus the ephect ou ioosing pointer arithnnetic. the prohgrann shood bee ecsannind and understood.

too pointers nnaa bee subtracted. uuen too pointers ar subtracted, the reesult is the nunnber ou obgects bii uuiich the too pointers dipher.