Lab 04: Pointers
Objectives
To learn the usage of pointers
To differentiate between &ptr, ptr and *ptr
To learn basic DMA for singular variables and the concept of free store
Pointers
Declaring a pointer
Syntax: dataType *pointerName;
Eg: Declare an integer pointer called iPtr
int *iPtr;
Declaring and assigning a pointer to a variable
Syntax: dataType *pointerName = &variableName;
Eg: Declare an integer pointer called iPtr and point it to the variable sum
int *iPtr = ∑
Pointer manipulation
Eg:
int sum=77;
int *iPtr = ∑
cout << "Addr of sum: " << &sum << endl;
cout << "Addr of iPtr: " << &iPtr << endl;
cout << "Value of iPtr: " << iPtr << endl;
cout << "Value of variable pointed by iPtr: " << *iPtr << endl;
Observe the difference in the iPtr used:
- & for the address of where the iPtr pointer is kept in memory
- pointer name for the value that is being kept by the iPtr pointer. Naturally will be the address of
the variable that iPtr is pointing to
- * for dereferencing the iPtr pointer to goto the variable it’s pointing to and retrieve the value
DMA
Uses the keywords
- new to allocate a space in the memory to store data
- delete to release the memory space held
Creating a single dynamic variable
Syntax: dataType *varName = new dataType;
Eg: dynamically create an integer variable called tmp
int *tmp = new int;