Docsity

Understanding Pointers in C++: Memory Addresses and Data Manipulation, Slides of Computer Programming

Partial preview of the text

Download Understanding Pointers in C++: Memory Addresses and Data Manipulation and more Slides Computer Programming in PDF only on Docsity!

  • Monday, April 23, 2012 Computer ProgrammingLecture

PointersMost of C++โ€™s power is derived frompointers.They allow different sections of code toshare information easily.Pointers enable complex data structureslike linked lists.

A pointer is a variable that holds a

Pointers memory address.

int x=5;int *xptr;

5 x of type int 0x0012F690^ 0x0012F

xptr of type int*

int x=5;int *xptr;xptr=&x; //points to x

5 x of type int 0x0012F

xptr of type int*

int x=5;int *xptr;xptr=&x; //points to x

x of type int^5 xptr of type int*

Pointer OperatorsThere are two special operators that are usedwith pointers: * and &The & is a unary operator that returns thememory address of its operand.int balance = 350;int *balptr;balptr = &balance;

The second operator * is the complement of &.It is a unary operator that returns the value ofvariable located at address specified by itsoperand.int balance = 350;int *balptr;balptr = &balance;int value;value = *balptr;

//what does value contain? Pointer Operators

PointersWhen a pointer is first allocated it does notpoint to anything.Trying to de-reference an un-initialized pointeris a serious runtime error.If you are lucky the dereference will crash orhalt immediately.If you are unlucky it will corrupt a random areaof memory โ€“ so that things go wrong after someindefinite time.

Pointers Make a memory drawing!

Output balance is: 3200Memory address where balance is stored is: 0012FF7C(Note memory address may be different when you run iton your machine)

int a, b;int *aptr, bptr; //Be careful!

int p;int x=12;p=&x;cout<<x<<endl;//Assign a value to the location pointed to by pp = 101;cout<<x<<endl;

//what is value of x? Assigning values through a pointercout<<*p<<endl;cout<<p<<endl;cout<<&x<<endl;

int *p;int x=12;p=&x;cout<<x<<endl;

//prints 12 //Assign a value to the location pointed to by p*p = 101;cout<<x<<endl;

//prints 101 cout<<*p<<endl;

//prints 101 cout<<p<<endl;

//prints 0012FF cout<<&x<<endl;

//prints 0012FF Assigning values through a pointer(Note memory address may be different when you run it on your machine)