Lecture 10 computer programming
Lecture 10 computer programming
ALLOCATION Section-I
* operator
Indirection operator or dereferencing operator
Returns a synonym, alias or nickname to which its operand points
& operator
Address of operator
Returns the address of its operand
POINTERS
Dereferencing
o A pointer variable has associated two values
1. A direct value, that is the address of a variable it is pointing. It can be
referenced by using the pointer name
2. And Indirect value, the value of the variable to which the pointer is pointing
o Dereferencing a pointer means accessing the value of the variable to which the
pointer is pointing (indirect value)
o The dereference operator * is used for this
o For example,
int x = 5;
int* ptr = &x;
int y = *ptr; // assign the value of x to y
POINTERS
Pointer Arithmetic
o Pointers can be incremented or decremented using arithmetic operations such as
++, --, +, -
o This allows traversal through arrays and dynamic data structures
o Pointer arithmetic works by using the size of the data type being pointed to
o When a pointer is incremented or decremented, it moves to the next or previous
memory location based on the size of the data type
o For example, if you have a integer pointer intPtr, incrementing it by 1 would
move it to the next memory location that can hold an integer value
o Since a integer variable typically takes 4 bytes, the pointer would move 4 bytes
forward
POINTERS
o Pointer arithmetic is not limited to just incrementing or decrementing by 1
o You can also add or subtract a pointer by a certain number (integer), which will
move it forward or backward by that many times the size of the data type
o One thing to note is that pointer arithmetic should only be performed on pointers
that are pointing to elements of an array or one element past the end of an
array
o If pointer arithmetic is done on a pointer that is not pointing to an array, the
behavior is undefined and can lead to errors or unpredictable results
POINTERS
Pointers and Arrays
o Arrays and pointers are closely related
o The name of an array is a pointer constant to the first element of the array
o When an array is accessed using an index, it is equivalent to dereferencing a
pointer to the array's first element
o For example,
int scores[10] = {87,98,93,87,83,76,86,83,86,77};
int *scorePtr = NULL;
scorePtr = scores;
POINTERS
o Element of the array at index n can also be accessed using the pointer (first
element) + integer n i.e
scores[5] is same as *(scoresPtr+5)
POINTERS
Task
Write a program
DYNAMIC MEMORY Lecture 10
ALLOCATION Section-II