Docsity

Understanding Pointers in C Programming, Slides of Computer Programming

Partial preview of the text

Download Understanding Pointers in C Programming and more Slides Computer Programming in PDF only on Docsity!

The structure of memory

^ Computer memory is a linear sequenceof addressable locations ^ Addresses are numbered starting atzero ^ In personal computers, the smallestaddressable unit is a byte (8 bits)

MainMemory(RAM)

ControlUnit (CU)Arithmetic-Logic Unit(ALU)CPU

0 - 34 - 7 100 -107108 -109 110 -121^ MemoryAddresses

instr1instr2.^.^. -75^254

... 101.

Memory Organization

program^ data

Pointer

^ Pointer is a variable that keeps anaddress of a variable ^ Need to learn four things aboutpointers^ ^

Declaration  Initialization  Assignment  Pointer’s arithmetic

Declaration

^ Pointers are declared by a name tagand * ^ Examples^ ^

int *xptr;^ ^ xptr is the pointer variable that can point to anyvariable of type int, means it can keep theaddress of an int variable  float *avg_ptr;^ ^ avg_ptr is a pointer variable that can keep theaddress of any float type variable

Assignment

^ A bit CONFUSING: assignment also uses*, do not confuse it with the pointerdeclaration int

marks

=^

int

*xptr;

xptr

=^

&marks;

*xptr

=^

/*^ marks

will

be^

equal

to^

Assigning Values to Pointers  Set pointer value directly^ ^ double x, *xp = &x;^ ^ *xp = 3.14;^ ^ Make sure pointer has been set to anallocated memory region  Setting pointer value to null^ ^ E.g., int *p = 0; int *p = NULL;

Pointer Examples

char *c; (pointer to char, not assigned)int b = 5; int *bptr = &b;char str[8]; char *s = str;

bptr

b s str[0]

str[7] 5

Arrays

^ Accessing array elements^ ^

E.g., int a[8];^ ^ a[0], a[1], … a[7]^ 

First entry has index 0

^ Array name = pointer to a memoryaddress

Pointer Examples int i = 0;

Pointer Examples 0

NULL

int i = 0;int intPtr = NULL; i*^

intPtr 0x

0x

0x

0x

int i = 0;

Pointer Examples 0

NULL

int i = 0;int intPtr = NULL;intPtr = &i; i*^

intPtr

0x

0x

0x

0x

Pointer Examples 0

0x

0x

0x

i^

intPtr 0x

0x

0x

0x

What do these expressions evaluate to? &i intPtrintPtri &intPtr*

Pointer Examples

0x i^

intPtr

0x

0x

0x

0x

0x

0x

What do these expressions evaluate to? &i^

0x

intPtrintPtri &intPtr*