BCSC 1102 Introduction to Programming Lecture 7
BCSC 1102 Introduction to Programming Lecture 7
Contents
1 Introduction to Pointers 2
1.1 Definition of a Pointer . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Benefits of Using Pointers . . . . . . . . . . . . . . . . . . . . . . 2
2 Pointer Basics 2
2.1 Pointer Declaration and Initialization . . . . . . . . . . . . . . . 2
2.2 Pointer Dereferencing . . . . . . . . . . . . . . . . . . . . . . . . 2
2.3 NULL Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
3 Pointer Arithmetic 3
3.1 Pointer Addition and Subtraction . . . . . . . . . . . . . . . . . . 3
3.2 Pointer Comparison . . . . . . . . . . . . . . . . . . . . . . . . . 3
1
1 Introduction to Pointers
1.1 Definition of a Pointer
A pointer is a variable that stores the memory address of another variable.
Pointers are a powerful feature in C that allow for dynamic memory manage-
ment, efficient handling of variables, and direct memory manipulation.
2 Pointer Basics
2.1 Pointer Declaration and Initialization
A pointer must be declared before it can be used to store the address of a
variable.
Syntax:
1 type * pointer_name ;
Example:
1 int * ptr ; // Declaration of an integer pointer
2 int x = 10;
3 ptr = & x ; // Initialization with the address of x
2
1 int * ptr = NULL ;
3 Pointer Arithmetic
3.1 Pointer Addition and Subtraction
Pointers can be incremented or decremented to point to the next or previous
memory location of the type they point to.
Example:
1 int x = 10;
2 int * ptr = & x ;
3 printf (" Address of x : % p \ n " , ptr ) ;
4 ptr ++; // Points to the next memory location
5 printf (" New address : % p \ n " , ptr ) ;
6 ptr - -; // Points back to the original address of x
7 printf (" Address of x : % p \ n " , ptr ) ;
3
1 void printIntValue ( void * ptr ) {
2 printf (" Integer value : % d \ n " , *( int *) ptr ) ;
3 }
4
5 int main () {
6 int x = 10;
7 void * ptr = & x ;
8 printIntValue ( ptr ) ; // Output : Integer value : 10
9 return 0;
10 }
• Local Scope: Pointers declared within a function are local to that func-
tion and cannot be accessed outside it.
• Global Scope: Pointers declared outside all functions are global and can
be accessed by any function in the program.
• Block Scope: Pointers declared within a block (e.g., within {}) are local
to that block.
Example:
1 int globalVar ; // Global variable
2
3 void function () {
4 int localVar ; // Local variable
4
5 {
6 int blockVar ; // Block - scoped variable
7 }
8 }
5 localVar ++;
6 staticVar ++;
7
11 int main () {
12 function () ; // Output : localVar : 1 , staticVar : 1
13 function () ; // Output : localVar : 1 , staticVar : 2
14 return 0;
15 }
5
1 int * c r e a t e D a n g l i n g P o i n t e r () {
2 int x = 10;
3 return & x ;
4 }
5
6 int main () {
7 int * danglingPtr = c r e a t e D a n g l i n g P o i n t e r () ;
8 printf ("% d " , * danglingPtr ) ; // Undefined behavior
9 return 0;
10 }