Docsity

Understanding Pointers, Memory Management, and Dynamic Allocation, Study notes of Computer Science

Partial preview of the text

Download Understanding Pointers, Memory Management, and Dynamic Allocation and more Study notes Computer Science in PDF only on Docsity!

Pointers

•^

Pointers use memory addresses asvalues

•^

Ordinary variables refer to memorylocations of various types^ –

Integer variable

int mint

–^

Double variable

double xval

–^

Character variable

char ch

•^

Pointer variable:

int * mptr

  • The value of this variable is the

location of an int

Address

Contents

‘C’

Pointer operations •^

Value-pointed-to:^ –

int * mptr

-^

*mptr

•^

Address-of^ –

mptr = & mint;

-^

The variable is reassigned tobe the location of mint

-^

Now:

*mptr

Address

Contents

‘C’

mint

Pointers and arrays •^

When you declare an array,memory is allocated for the array.^ –

double values[ 7 ]

•^

Actually, the name of the array is apointer to the first location^ –

Equivalently, you could declare apointer

-^

int * valuesPtr;valuesPtr = values;

•^

Pointer arithmetic can be used toaccess elements of the array

•^

Can be Dangerous!

Structures with Pointer as values •^

You can create structures likelinked lists:^ –

struct entry{

int

value;

struct entry *next;

}

-^

Example: Using a linked list:struct entry node1, node2;node1.next = &node2;