Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
39 views52 pages

MODULE 4 Pointers

Pointers in C store the address of other variables. Pointers allow low-level memory access and dynamic memory allocation. Pointer variables hold the address of the variable they are pointing to. Pointers must be declared, initialized, and dereferenced to access the value of the pointed variable.

Uploaded by

ABHISHEK TR
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)
39 views52 pages

MODULE 4 Pointers

Pointers in C store the address of other variables. Pointers allow low-level memory access and dynamic memory allocation. Pointer variables hold the address of the variable they are pointing to. Pointers must be declared, initialized, and dereferenced to access the value of the pointed variable.

Uploaded by

ABHISHEK TR
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/ 52

POINTERS

A pointer is defined as a derived data type that can store the


address of other C variables or a memory location.
The use of pointers allows low-level memory access, dynamic memory
allocation, and many other functionality in C.

Declaring pointers:

Pointer declarations use the * operator. They follow this format:

typeName * variableName;

int n; // declaration of a variable n

int * p; // declaration of a pointer, called p


■ A normal variable ‘var’ has a memory address of 1001 and holds a value 50.
■ A pointer variable has its own address 2047 but stores 1001, which is the
address of the variable ‘var’
How to Use Pointers?

The use of pointers in C can be divided into three steps:


1. Pointer Declaration
2. Pointer Initialization
3. Pointer Dereferencing
1. Pointer Declaration

To declare a pointer, use the ( * ) dereference operator before its name.


Example
int *ptr;
The pointer declared here will point to some random memory address as it is not
initialized. Such pointers are called wild pointers.
2. Pointer Initialization

Pointer initialization is the process where assign some initial value to the pointer
variable.
The ( & ) addressof operator to get the memory address of a variable and then store
it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;
3. Pointer Dereferencing
#include <stdio.h>

void pointer()
{
int var = 10;

// declare pointer variable


int* ptr;

// note that data type of ptr and var must be same


ptr = &var;

// assign the address of a variable to a pointer


printf("Value at ptr = %p \n", ptr);
printf("Value at var = %d \n", var);
printf("Value at *ptr = %d \n", *ptr);
}

void main()
{
pointer();

}
Advantage of pointer

● Without pointers, dynamic memory allocations are impossible.

● Pointers can be used to change the value permanently to a variable because pointer access the address of

a variable.

● Pointer provides an alternate way to access array elements.


NULL Pointer

A Null Pointer is a pointer that does not point to any memory location. It stores the base
address of the segment.

Null means that the pointer is referring to the 0th memory location.

If we do not have any address which is to be assigned to the pointer, then it is known as
a null pointer. When a NULL value is assigned to the pointer, then it is considered as a
Null pointer.
create a pointer *ptr and assigns a
NULL value to the pointer, which
#include <stdio.h> means that it does not point any
int main() variable. After creating a pointer
{ variable, we add the condition in
int *ptr=NULL; which we check whether the value of
if(ptr!=NULL) a pointer is null or not.

{
printf("value of ptr is : %d",*ptr);
}
else
{
printf("Invalid pointer");
}
return 0;
}
Void Pointer A pointer to void means a generic pointer that can point to any data type.
if we declare the int pointer, then this int pointer cannot point to the
float variable or some other type of variable, i.e., it can point to only int
type variable. To overcome this problem, use a pointer to void.
Syntax of void pointer
void *pointer name;
Size of the void pointer in C
1. #include <stdio.h>
2. int main()
3. {
4. void *ptr = NULL; //void pointer
5. int *p = NULL;// integer pointer
6. char *cp = NULL;//character pointer
7. float *fp = NULL;//float pointer
8. //size of void pointer
9. printf("size of void pointer = %d\n\n",sizeof(ptr));
10. //size of integer pointer
11. printf("size of integer pointer = %d\n\n",sizeof(p));
12. //size of character pointer
13. printf("size of character pointer = %d\n\n",sizeof(cp));
14. //size of float pointer
15. printf("size of float pointer = %d\n\n",sizeof(fp));
16. return 0;
17. }
Passing Pointers to a Function
Passing the pointers to the function means the memory location of the variables is passed
to the parameters in the function, and then the operations are performed.
Arguments Passing without pointer
#include <stdio.h>

void swap(int a, int b)


{
int temp = a;
a = b;
b = temp;
}

// Driver code
int main()
{
int a = 10, b = 20;
swap(a, b);
printf("Values after swap function are: %d, %d",
a, b);
return 0;}
Arguments Passing with pointers

#include <stdio.h>
void swap(int* a, int* b)
{ A pointer is passed instead of a variable and its
int temp; address is passed instead of its value.
temp = *a; Any change made by the function using the
*a = *b; pointer is permanently stored at the address of
*b = temp; the passed variable.
}

int main()
{
int a = 10, b = 20;
printf("Values before swap function are: %d, %d\n",
a, b);
swap(&a, &b);
printf("Values after swap function are: %d, %d",
a, b);
return 0; }
Pointers and one-dimensional arrays

The compiler allocates Continuous memory locations for all the elements of the array.
The base address = first element address (index 0) of the array.
For Example − int a [5] = {10, 20,30,40,50}
If ‘p’ is declared as integer pointer, then, an array ‘a’ can be pointed by
the following assignment −

p = a;
(or) p = &a[0];

Every value of 'a' is accessed by using p++ to move from one element
to another element. When a pointer is incremented, its value is
increased by the size of the datatype that it points to. This length is
called the "scale factor"
P = &a[0] = 1000

P+1 = &a[1] = 1004

P+2 = &a[2] = 1008

P+3 = &a[3] = 1012

P+4 = &a[4] = 1016


Address of an element is calculated using its index and the scale factor of the datatype

Address of a[3] = base address + (3* scale factor of int)

= 1000 + (3*4)

= 1000 +12

= 1012
#include<stdio.h>
main ( ){
int a[5];
int *p,i;
printf ("Enter 5 Elements");
for (i=0; i<5; i++)
scanf ("%d", &a[i]);
p = &a[0];
printf ("Elements of the array are");
for (i=0; i<5; i++)
printf("%d", *(p+i));
malloc()
allocates requested number of bytes and return pointer of type void to allocated
memory.
calloc( )
dynamically allocates memory space for the array, initializes to zero and return a
pointer to the memory location
free( )
deallocates previously used memory
realloc( )
modify the size of previously allocated memory
Dynamic Memory Allocation in C using malloc(), calloc(), free() and
realloc()
C provides some functions to achieve these tasks.

There are 4 library functions provided by C defined under <stdlib.h> header file to
facilitate dynamic memory allocation in C programming.

1. malloc()
2. calloc()
3. free()
4. realloc()
C malloc() method

The “malloc” or “memory allocation” method in C is used to dynamically


allocate a single large block of memory with the specified size. It returns a pointer
of type void which can be cast into a pointer of any form. It doesn’t Initialize
memory at execution time so that it has initialized each block with the default
garbage value initially.

Syntax of malloc() in C: ptr = (cast-type*) malloc(byte-size)

ptr = (int*) malloc(100 * sizeof(int));

Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer
ptr holds the address of the first byte in the allocated memory.
calloc() method
1. “calloc” or “contiguous allocation” method in C is used to dynamically allocate the
specified number of blocks of memory of the specified type. it is very much similar to
malloc() but has two different points and these are:
2. It initializes each block with a default value ‘0’.
3. It has two parameters or arguments as compare to malloc().

Syntax of calloc() in C: ptr = (cast-type*)calloc(n, element-size);

here, n is the no. of elements and element-size is the size of each


element
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of the
float.
free() method

“free” method in C is used to dynamically de-allocate the memory.


The memory allocated using functions malloc() and calloc() is not
de-allocated on their own. Hence the free() method is used, whenever
the dynamic memory allocation takes place. It helps to reduce
wastage of memory by freeing it.

Syntax of free() in C: free(ptr);


realloc() method
“realloc” or “re-allocation” method in C is used to dynamically change the memory
allocation of a previously allocated memory. In other words, if the memory previously
allocated with the help of malloc or calloc is insufficient, realloc can be used to
dynamically re-allocate memory. re-allocation of memory maintains the already
present value and new blocks will be initialized with the default garbage value.

Syntax of realloc() in C: ptr = realloc(ptr, newSize);

where ptr is reallocated with new size 'newSize'


Example ptr = (int*)realloc(ptr, n * sizeof(int)
printf("\nEnter array elements:\n");
#include <stdio.h>
for(i = 0; i < size; i++)
#include <stdlib.h>
{ scanf("%d", numPtr + i); }
int main() printf("\nElements of array you
{ entered:\n");
int size, resize, i; for(i = 0; i < size; i++)
int *numPtr; //declaring pointer { printf("%3d", *(numPtr + i)); }
variable printf("\n\nEnter new size of array: ");
scanf("%d", &resize);
printf("Please enter size of array: numPtr = realloc(numPtr, resize *
"); sizeof(int));
scanf("%d", &size); if(numPtr == NULL)
{ printf("\nError !!! (Not enough
//allocation memory for array
space)");
numPtr = (int*) malloc(size *
sizeof(int)); exit(0);
}
//checking whether memory is allocated printf("\n\nElements of resized
or not array:\n");
if(numPtr == NULL) for(i = 0; i < resize; i++)
{ {
printf("\nError !!! (Not enough printf("%3d", *(numPtr + i));
space)"); }
exit(0); printf("\n\n");
} free(numPtr); //free reserved memory
return 0;
Operations on Pointers-C

Pointers are variables that contain the memory address of another variable.
Since an address in a memory is a numeric value we can perform arithmetic operations
on the pointer values.

■ Incrementing/Decrementing a pointer
■ Addition/Subtraction of a constant number to a pointer
■ Subtraction of one pointer from another
■ Comparison of two pointers
Incrementing/Decrementing a Pointer

Any pointer variable when incremented points to the next memory location of its type.

int a = 5,*x;

x = &a;

x++;
let us assume that the memory location where a is stored is 63420.

So, x now contains the value 63420.

Also,x stores the address of an integer variable that has a size of 4 bytes.

Once the value of x is incremented it does not store 63421, rather it stores
63424 which is the next memory location for the integer variable.

Thus, the pointer gets incremented according to the data type of the value it
stores.
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u
\n",p); // p will get incremented by 4 bytes.
return 0;
}
Addition/Subtraction of a constant number to a pointer

32-bit

For 32-bit int variable, it will add 2 * number.

64-bit

For 64-bit int variable, it will add 4 * number.

new_address= current_address + (number * size_of(data type))


#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number
variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is
%u \n",p);
return 0;
}
Subtraction of one pointer from another: instead of subtracting a number, we can
also subtract an address from another address (pointer). This will result in a number.

1. #include<stdio.h>
2. void main ()
3. {
4. int i = 100;
5. int *p = &i;
6. int *temp;
7. temp = p;
8. p = p + 3;
9. printf("Pointer Subtraction: %d - %d = %d",p, temp, p-temp);
10. }
two pointers can be compared by using the comparison
operators in This can be implemented by using all operators in
C >, >=, <, <=, ==, !=.
It returns true for the valid condition and returns false for the
unsatisfied condition.
int main()
{

int arr[5];

int* ptr1 = &arr;


int* ptr2 = &arr[0];

if (ptr1 == ptr2) {
printf("Pointer to Array Name and First Element "
"are Equal.");
}
else {
printf("Pointer to Array Name and First Element "
"are not Equal.");
}
return 0;
}
POINTERS AND MULTIDIMENSIONAL ARRAYS

Since a one dimensional array can be


represented in terms of a pointer(the array
name) and anoffset(the subscript), it is
reasonable to expect that a multidimensional
array can also be represented with an
equivalent pointer notation.
#include <stdio.h>
#define ROW 3
#define COL 3
int main(void)
{
// 2d array
int aiData [ROW][COL] = { { 9, 6, 1 }, { 144, 70, 50 }, {10, 12,
78} };
int *piData = NULL; //pointer to integer
int iRow =0, iCol =0;
piData = &aiData[0][0]; //You can also write *aiData
for (iRow = 0; iRow < ROW; ++iRow) //Loop of row
{
for (iCol = 0; iCol < COL; ++iCol)// Loop for coloum
{
//Read element of 2D array
printf("aiData[%d][%d] = %d\n",iRow,iCol, *(piData + ( iRow
* COL) + iCol));
}
}
return 0;
Array of pointers

Where arr[0] holding the address of the variable a. i.e. arr[0] = 1024
*arr[0] -> *1024 -> value stored at the memory address 1024 is 10. So, *arr[0] = 10.
Similarly, *arr[1] = 20, *arr[2] = 30 and so on.
An array name is generally treated as a pointer to the first element of the array
and if we store the base address of the array in another pointer variable, then
can easily manipulate the array using pointer arithmetic in a C Program.
Syntax:*(arr + i)

● * is a dereferencing operator used to extract the value from the


address (arr + i).
● *(arr + i) is the same as arr[i] in a C Program.
● arr represents the array name and i represents the index value.
#include <stdio.h> ● (arr + i) represents the address of the value at index i, so
*(arr + i) will give the value at ith index (address(arr + i) =
int main() address(arr[i])), it is used to print the addresses of the array
{ elements as the value of i changes from 0-4.
int arr[5] = {2, 4, 6, 8, 10}, i;

for(i = 0; i < 5; i++)


{

printf("[index %d] Address : %u, Value : %d\n", i, (arr +


i), *(arr + i));
} ● * is a dereferencing operator used for printing the value at
the provided address. *(arr + i) will print the values of the
return 0; array at consecutive addresses as the value of i changes
} from 0-4.
Variable Length Argument in C
Variable length argument is a feature that allows a function to receive any number of
arguments. Variadic functions are functions that can take a variable number of arguments

1) Sum of given numbers. 2) Minimum of given numbers.

To solve the above problem need function to handle variable number of


arguments according to requirement
Variable number of arguments are represented by three dotes (…)

Syntax: int function_name(data_type variable_name, ...);


Values of the passed arguments can be accessed through the header file named as:
#include <stdarg.h>
int func(int, ... ) {
.
.
.
}
int main() {
func(1, 2, 3);
func(1, 2, 3, 4);
}
1. va_start: Initialising the Argument List
va_start is the starting point. It initialises a va_list to point to the first of
the variable arguments.
va_start(args, format);

Here, args is the va_list variable, and format is the last named argument
of our function.

When a function is called, the arguments are typically placed onto a stack. va_start sets
up the va_list to point to the first variable argument on this stack.
2. va_arg: Retrieving Arguments
va_arg fetches the next argument in the list. It moves the pointer forward by the size of the
type specified.

It requires two arguments:


● The va_list variable
● The desired type of the next argument

va_arg(args, int)
3. va_end: Cleaning Up
va_end is the counterpart to va_start. It cleans up the memory associated with the va_list.
#include <stdarg.h>
#include <stdio.h>
int AddNumbers(int n, ...)
{
int Sum = 0;
va_list ptr;
va_start(ptr, n);
for (int i = 0; i < n; i++)
Sum += va_arg(ptr, int);
va_end(ptr);
return Sum;
}
int main()
{
printf("\n\n Variadic functions: \n");
printf("\n 1 + 2 = %d ",
AddNumbers(2, 1, 2));
printf("\n 3 + 4 + 5 = %d ",
AddNumbers(3, 3, 4, 5));
printf("\n 6 + 7 + 8 + 9 = %d ",
AddNumbers(4, 6, 7, 8, 9));
printf("\n");

You might also like