pointers in c

16
‘*’ , ‘&’ Pointers In C

Upload: guestb811fb

Post on 31-Oct-2014

3 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Pointers in c

‘*’ , ‘&’ Pointers In C

Page 2: Pointers in c

About me

Sriram kumar . K

III rd year CSE

Email - [email protected]

Page 3: Pointers in c

What is a Pointer ?

Page 4: Pointers in c

X1000

X1004

X1008

X100c

x1010

Who does a memory look like ?

X1000

X1001

X1002

X1003

Address Locations

Page 5: Pointers in c

Operators used in Pointers

* &AddressDereferencing

(Address of)(Value of)

Page 6: Pointers in c

Int i=3;

Address of ‘i’ Value of ‘i’

X1000 x1004 x1008 x100c x1010 x1014

variable

i

3(Value of i)

Address of i

‘&i’ ‘*i’

The value ‘3’ is saved in the memory location ‘x100c’

Page 7: Pointers in c

Syntax for pointers

(pointer type declaration)

type *identifier ;

Example

Char *cp ;

Int *ip ;

Double *dp ;

Page 8: Pointers in c

Pointer Assignment

Int i = 1 , *ip ; //pointer declaration

ip = &i ; //pointer assignment

*ip = 3 ; //pointer assignment

Page 9: Pointers in c

Pointer ArithmeticLets take this example program

#include<stdio.h>

Void main()

{

Int a [5]={1,2,3,4,5} , b , *pt ;

pt = &a[0];

pt = pt + 4 ;

b=a[0] ;

b+=4 ;

}

a[0]

X1000 x1004 x1008 x100c x1010

X1000 x1004 x1008 x100c x1010

pt

a[2]a[1] a[4]a[3]

a[0] a[2]a[1] a[4]a[3]b

b = 1

b=1+4

b= 5

Page 10: Pointers in c

Lets Take an Example and See how pointers work

#include<stdio.h>

Void main()

{

Int i=3;

Int *j;

j=&i;

Printf(“i=%d”i);

Printf(“*j=%d”*j);

}

Page 11: Pointers in c

X1000 x1004 x1008 x100c x1010 x1014

3Memory

variables Int iInt *j

Int i=3;

Int *j;

j = &i;

x100c

Create an integer variable ‘i’ and initialize it to 3

Create a pointer variable ‘j’- create value of ‘j’

Initialize the pointer value of ‘j’ to the address of ‘i’

Page 12: Pointers in c

X1000 x1004 x1008 x100c x1010 x1014

Memory

variables Int iInt *j

Output screenPrintf(“i=%d” i);

We know j=&i

So *j=*(&i) value of (address of i)

(i.e.) value in address (x100c)

Printf(“i=%d” i);

i=3*j=3

Printf(“*j=%d” *j);Printf(“*j=%d” *j);

x100c 33

Page 13: Pointers in c

Void main(){int num=10;int* pnum=NULL;pnum = &num;*pnum += 20;printf("\nNumber = %d", num);printf("\nPointer Number = %d", *pnum);}

Predict the output of this code

Page 14: Pointers in c

Number = 10

Pointer Number = 30

Page 15: Pointers in c
Page 16: Pointers in c