0% found this document useful (0 votes)
11 views36 pages

Pointers

The document provides a comprehensive introduction to pointers in C programming, detailing their definition, usage, and importance in memory management. It covers pointer operators, pointer arithmetic, pointers with arrays, and the distinction between pointer to an array and an array of pointers. Additionally, it discusses passing pointers to functions, returning pointers from functions, and pointers to structures and functions, along with practical examples and resources for further study.

Uploaded by

shihab khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views36 pages

Pointers

The document provides a comprehensive introduction to pointers in C programming, detailing their definition, usage, and importance in memory management. It covers pointer operators, pointer arithmetic, pointers with arrays, and the distinction between pointer to an array and an array of pointers. Additionally, it discusses passing pointers to functions, returning pointers from functions, and pointers to structures and functions, along with practical examples and resources for further study.

Uploaded by

shihab khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Pointers

CSE 109

Prepared By : Mashiat Mustaq


Edited By: Md. Nurul Muttakin
Introduction to Pointers

● A variable that holds the memory address of another object

● Example :
○ type *var_name;
○ Here type/base type specified the type of the object the
pointer can point to
○ Such as: int *p; here p is a pointer to an integer
Introduction to Pointers

Pointer Operators
● & : returns the address of the variable it precedes
● * : returns the value stored at the address it precedes

int *p, q;
q = 199;
p = &q;
printf("%d", *p);
Introduction to Pointers : Indirection

When a variable’s value is referenced through a pointer

int *p, q;
p = &q;
*p = 199; Indirection
printf("%d", q);
printf(“%p”, p);
Introduction to Pointers

Why base type is important?


→ Compiler determines the number of bytes to copy when an
indirect assignment is made based on base type

int q;
double *fp; Problem?
fp = &q;
*fp = 100.23;
Introduction to Pointers

Why base type is important?


→ Compiler determines the number of bytes to copy when an
indirect assignment is made based on base type

int q;
double *fp; Problem?
fp = &q; Overwrites the adjacent additional
*fp = 100.23; 4 bytes to q
Introduction to Pointers

Why should we initialize a pointer as NULL always?

→ If we access an unassigned pointer, it points to a garbage


value and it is dangerous.

int *p;
*p = 10; Unassigned pointer,
program will crash
Example

What will happen with the following code?

int *p;
double q, temp;
temp = 1234.34;
p = &temp;
q = *p;
printf("%f", q);
Pointer Operators

● Arithmetic operators : +, ++, -, --


● Only integer quantities can be added / subtracted
● Performs relative to the base type

int *p;

p = 200 (address)

p++;

p = 204 (address)
Pointer Operators

● Arithmetic operators : +, ++, -, --


● Only integer quantities can be added / subtracted
● Performs relative to the base type

int *p;
P points to the 200th integer
p = p + 200; past the one to which
previously pointed
Pointer Operators

● Difference between *p++ and (*p)++ ?


Pointer Operators

● Difference between *p++ and (*p)++ ?

● *p++ first increments p then obtains the value at the new


location
● (*p)++ increments the value through indirection
Pointer Operators

char *cp, ch;


int *ip, i;
float *fp, f;
double *dp, d;

cp = &ch; ip = &i; fp = &f; dp = &d;

printf("%p %p %p %p\n", cp, ip, fp, dp);

cp++; ip++; fp++; dp++;

printf("%p %p %p %p\n", cp, ip, fp, dp);


Pointer with Arrays

● Array name without index → pointer to the start of the array


● Function only accepts pointers for arrays

int a[5] = {10, 20, 30, 40, 50};


int *p;
p = a;

printf( "%d %d %d\n" , *p, *(p+1), *(p+2));


printf("%d %d %d\n" , a[0], a[1], a[2]);
Pointer with Arrays

● Multidimensional array
● float balance[10][5] → how to access balance[3][1] using pointer?
Pointer with Arrays

● Multidimensional array
● float balance[10][5] → how to access balance[3][1] using pointer?

float *p;
p = (float *) balance; p = balance might
not work in all
*(p + (3 * 5) + 1) compilers as p
might point to the
first row and p+1
will point to the
second row
Pointer with Arrays : Indexing

char str[] = "Pointers are fun";


char *p;

p = str;

for(int i = 0; p[i]; i++)


printf("%c", p[i]);
Pointer with Arrays : Problems

● Print a string in reverse order using pointers


Arrays of pointers

Declaration : type *array_name[size];


int var[] = {10, 100, 200};
int i, *ptr[3];
for ( i = 0; i < 3; i++) {
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < 3; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
Arrays of pointers
int i, j; printf("Using Pointer:");
int M = 3, N = 4; for ( i = 0; i < M * N; i++) {
int *p; if ( i%N == 0) printf("\n");
int a[3][4] = {1, 2, 4, 5, 3, 0, 6, 8, 7, 9, 11, 10}; printf("%d ", *(p+i));
}
printf("Using Array:\n"); printf("\n");
for ( i = 0; i < M; i++) {
for ( j =0; j < N; j++ ) { p = a[0];
printf("%d ", a[i][j]); printf("Using Pointer2:\n");
} for ( i = 0; i < M; i++) {
printf("\n"); for ( j =0; j < N; j++ ) {
} printf("%d ", * ( p + N * i + j ) );
//p = a; // not recommended }
// p = (int *) a ; // better than p = a printf("\n");
// p = a[0]; }
p = &a[0][0];
Pointer to an array VS array of pointers

● int* arr[3]
○ arr is an array of 3 pointers to integers.
○ Each element of arr is a pointer that can point to an integer.
○ It's often used when you need an array where each element is a
pointer, and each pointer can point to a different memory location.
● int (*arr)[3]
○ arr is a pointer that can point to the beginning of an array of 3
integers.
○ It's often used to represent a 2D array, and pointer arithmetic can be
used to navigate through rows and columns.
Pointer to an array example
int a[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
int (*p)[3]; // Declare a pointer to an array of 3 integers

p = a; // This assigns the address of the first row of the array to p


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", *(*(p + i) + j));
}
printf("\n");
}
Pointer with Strings

● Variable length strings


● A char pointer indicates to the address of the string
in string table of the program.

char *p = "one two three";


printf(p);
Arrays of pointers

Declaration : type *array_name[size];

// Declaring an array of pointers to characters


char *names[] = {"John", "Jane", "Doe"};

// Accessing and printing the second name


printf("%s\n", names[1]); // Outputs: Jane
// names[1][1] → a
Arrays of pointers

There are 10 students in a class. Each student has a


roll number (starting from 1) and a name. You need to
build a program that outputs the name of each student
if the given input is the roll number using array of
pointers.
Passing pointer to a function

double getAverage(int *arr, int size);


double getAverage(int *arr, int size) {
int main () {
int i, sum = 0;
double avg;
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
for (i = 0; i < size; ++i) {
double avg;
sum += arr[i];
}
/* pass pointer to the array as an
argument */
avg = (double)sum / size;
avg = getAverage( balance, 5 ) ;
return avg;
}
/* output the returned value */
printf("Average value is: %f\n", avg );
return 0;
}
Passing pointer to a function
int main() {
void sort(int *a, int n){
int *a, i, j, n;
// Sorting the array using pointer // Input the number of elements to store in the
int tmp; array
for (int i = 0; i < n; i++) { scanf("%d", &n);
for (int j = i + 1; j < n; j++) { // Input elements into the array
if (*(a + i) > *(a + j)) { for (i = 0; i < n; i++) {
// Swap elements if they are in the printf(" element - %d : ", i + 1);
wrong order scanf("%d", a + i);
}
tmp = *(a + i);
*(a + i) = *(a + j); sort(a, n);
*(a + j) = tmp;
} // Displaying the sorted array elements
} for (i = 0; i < n; i++) {
printf(" element - %d : %d \n", i + 1, *(a + i));
}
}
} }
Passing pointer to a function
int main() {
// Function to process a 2D array
int a[2][3] = {
void processArray(int (*arr)[3], int rows,
{1, 2, 3},
int cols) { {4, 5, 6}
for (int i = 0; i < rows; i++) { };
for (int j = 0; j < cols; j++) {
printf("%d ", arr[i][j]); // Pass the 2D array to the function
} processArray(a, 2, 3);
for (int i = 0; i < 2; i++) {
printf("\n");
for (int j = 0; j < 3; j++) {
}
printf("%d ", a[i][j]);
}
arr[1][1] = 11; printf("\n");
} }
}
Return pointer from a function

int* fun()
{
static int A = 10;
return (&A);
}

int main()
{
int* p;
p = fun();

printf( "%p\n" , p);


printf( "%d\n" , *p);
return 0;
}
Return pointer from a function

int* fun()
{
If we used ‘int A’ (local
static int A = 10;
return (&A); variable) inside the
} function, it would have
gone outside scope
once the function exits
int main()
→ Segmentation fault
{
int* p;
p = fun();

printf( "%p\n" , p);


printf( "%d\n" , *p);
return 0;
}
Pointer to Pointer

Pointer to
Pointer Variable
pointer

char **mp, *p, ch;

p = &ch;
mp = &p;
**mp = 'A';
Pointer to Structure
struct Point {
int x;
int y;
};
int main() {
struct Point p1 = {10, 20};
struct Point *ptr = &p1;
printf("x = %d, y = %d\n", ptr->x, ptr->y);
ptr->x = 30;
ptr->y = 40;
printf("Updated x = %d, y = %d\n", ptr->x, ptr->y);
return 0;
}
Pointer to Function

A pointer to a function in C is used to store the address of a


function.

- It allows dynamic function calls.


- Useful for callbacks and passing functions as arguments.
- Syntax: `return_type (*pointer_name)(parameter_list);`
Pointer to Function
Example Declaration:
```
int (*funcPtr)(int, int);
```

- `int`: Return type of the function.


- `(*funcPtr)`: Pointer to a function.
- `(int, int)`: Parameters of the function.
Pointer to Function
```
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int (*funcPtr)(int, int);
int main() {
funcPtr = add;
printf("Sum: %d\n", funcPtr(5, 3));
return 0;
}
```
- Output: `Sum: 8`
- `funcPtr` points to `add` and calls it dynamically.
Resources for study

● https://www.tutorialspoint.com/cprogramming/c_pointers
.htm
● https://www.scaler.com/topics/c/array-of-pointers-in-c/

You might also like