0% found this document useful (0 votes)
34 views

Programming in C - Pointers

Pointers in C - A comprehensive note

Uploaded by

leninantony2008
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Programming in C - Pointers

Pointers in C - A comprehensive note

Uploaded by

leninantony2008
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Programming in C

Module III

Contents:Pointers – Fundamentals – declaration, Initialization, accessing of pointer variables -Pointer


arithmetic – Passing pointers to Functions – dynamic memory allocation - Arrays and Pointers -
Strings and Pointers – Array of Pointers.

Ref: Programming in ANSI C - E Balagurusamy - 6Ed page 369


________________________________________________________________________________

Pointers:
● A pointer is a derived data type in C.
● A pointer is a variable that stores the memory address of another variable.
● Instead of holding a data value directly, a pointer holds the location where the data is stored.
This allows for efficient manipulation and access of data in the memory.
● Pointer Declaration:
○ Pointers are declared with the datatype of the data it points to.
○ datatype *pointername;
○ Eg: int *ptr;
○ The ‘*’ symbol can appear anywhere between the datatype and the pointer name.
Hence the following declarations are also valid.
int* ptr;
int * ptr;
○ Here ptr is a pointer variable which can be used to point to an integer variable.
○ The symbol * is used to denote a pointer variable. Its meaning is ‘value at address’.
○ This operator ‘*’ is called the indirection operator or dereferencing operator.
○ Assigning the address of a normal variable to a pointer variable can be done by the &
symbol. Here the meaning of the symbol ‘&’ is ‘address of’.
○ Eg: int var=50;
ptr = &var;
● Say, the address of the variable var is 1001. By the statement ptr=&var; this address is
stored at the pointer ptr. Thus the variable var can be now accessed with the pointer as
*ptr. That means, if the value *ptr is changed, the value of var will be changed,
because both denote the same value.

S3 CT, GPTC Cherthala Programming in C, Module 3 1


○ Here, if we print ptr and *ptr, the result will be 1001 and 50 respectively.
○ If we assign *ptr = 15; and prints the variable var, the value will be 15.

● Pointer Initialization:
○ The pointer can be assigned with the address of a variable when it is declared. This is
called pointer initialization.
○ Eg: int var = 10;
int *ptr = &var; // pointer initialization
● We can assign many pointers to the same variable, provided all are of the same datatype.
○ Eg: int x;
int *p1=&x, *p2=&x, *p3=&x;

● Also we can use a pointer to point to many variables, one at a time, provided all are of the
same type.
○ Eg: int x, y, z, *p;

p = &x;

p = &y;

p = &z;

Advantages of using pointers

S3 CT, GPTC Cherthala Programming in C, Module 3 2


Pointer Arithmetic
● Pointer arithmetic allows us to use the values pointed by the pointers in arithmetic and
comparison operations. If p1 and p2 are two properly initialized pointers, the following
arithmetic expressions are valid. Here the values pointed by the pointers are used.
y = *p1 * *p2; //same as (*p1) * (*p2)
sum = sum + *p1;
z = 5* – *p2/ *p1; //same as (5 * (– (*p2)))/(*p1)
*p2 = *p2 + 10;
● The pointers themselves can be used in arithmetic. p1 + 4, p2 – 2 and p1 – p2 are all allowed.
If p1 and p2 are both pointers to the same array, then p2 – p1 gives the number of elements
between p1 and p2. But p1 + p2 is illegal. Ie, addition of two pointers is illegal.
● If ptr is a pointer to an element in an array, the ptr++ will increment the pointer by the length
of one element and ptr will point to the next element in the array. Similarly ptr--, ptr+=1 also
can be used to traverse through arrays.

Passing pointers to Functions


● Variables can be passed to a function in two ways; call by value and call by reference.
● In call by reference, we pass addresses to a function and the parameters receiving the
addresses should be pointers.
● Eg 1: Write a function increment which increments the parameter by 1.
void increment ( int *p )
{
*p = *p + 1;
}
void main( )
{
int m = 10;
printf(“m is %d \n”, m); // prints 10
increment(&m);
printf(“m is now %d \n”, m); // prints 11
}

S3 CT, GPTC Cherthala Programming in C, Module 3 3


● Here the address of the variable m is passed to the pointer p in the function increment( ).
Changing the value pointed by the pointer in turn changes the value of m. As this method
passes the variables as address to pointers, this method is also called call by address or pass
by pointers.
● Eg 2: Write a function swap( ) which receives two pointers to two integers and
interchanges the values of those two integer variables.
void swap ( int *p, int *q )
{
int temp = *p;
*p = *q;
*q = temp;
}
void main( )
{
int m = 10, n = 15;
printf(“Before swap, m=%d, n=%d \n”, m); // prints 10, 15
swap(&m, &n);
printf(“After swap, m=%d, n=%d \n”, m); // prints 15, 10
}
● Eg 3: Write a function which accepts two pointers and returns a pointer to the largest number.
int* largest ( int *p, int *q )
{
if (*p > *q)
return p;
else
return q;
}
void main( )
{
int m = 10, n = 15,*r;
r = largest(&m, &n);
printf("Largest = %d \n", *r);
}

Dynamic Memory Allocation


● The memory space requirement for local and global variables including arrays are allotted
during compile time.
● But in some cases, the space required for a variable, especially an array, may not be exactly
specified during compile time, rather it can be obtained during run time only.
● In such cases, the memory space is allotted during runtime and this process is called
dynamic memory allocation.
● Dynamic memory allocation helps to use the available memory intelligently and efficiently.
● When a C program is loaded into memory, it will have a Permanent Storage Area containing
the program instructions and global and static variables, a Stack containing the local variables
and a free area called the Heap.
● During the dynamic memory allocation, the memory space is allocated from the Heap
area.
● The major dynamic memory management functions available in the stdlib.h header file are
given below.
S3 CT, GPTC Cherthala Programming in C, Module 3 4
○ malloc - allocates a specified amount of memory but does not initialize it, meaning the
memory block contains whatever values were previously in that location.
○ calloc - allocates a specified amount of memory and initializes all bits to zero.
○ realloc - modifies the previously allocated space.
○ free - Frees the space previously allocated by malloc, calloc or realloc.
● malloc (“memory allocation”)
○ The malloc function reserves a single block of memory of specified size and returns
a pointer of type void.
○ This pointer can be typecasted to the required type.
○ Syntax: ptr = (cast-type *) malloc(byte-size);
where ptr is a pointer of type cast-type, byte-size is the size of memory space
required.
○ If the request fails due to non availability of memory, it will return NULL.
○ Eg 1: x = (int *) malloc (100 *sizeof(int));
■ On successful execution of this statement, a memory space equal to “100 times
the size of an int” bytes is reserved and the address of the first byte of the
allocated memory is assigned to the pointer x of type int. This statement can be
used to create a dynamic integer array of size 100.
○ Eg 2: cptr = (char*) malloc(10);
■ It allocates 10 bytes of space for the pointer cptr of type char. It can store a
string of name cptr with maximum size 10 characters.
● calloc (“contiguous allocation”)
○ calloc is a memory allocation function that is normally used for requesting memory
space at run time for storing derived data types such as arrays and structures.
○ While malloc allocates a single block of storage space, calloc allocates multiple
blocks of storage, each of the same size, and then sets all bytes to zero.
○ Syntax: ptr = (cast-type *) calloc (n, elem-size);
■ It allocates contiguous space for n blocks, each of size elem-size bytes.
■ All bytes are initialized to zero and a pointer to the first byte of the allocated
region is returned.
■ If there is not enough space a NULL is returned.
○ Eg: *ptr = (int *)calloc(10, sizeof(int));
■ Allocates memory for an array of 10 integers and initializes to 0.
● free
○ If we dynamically allocate memory, it is our responsibility to free it after use.
○ We can release that block of memory for future use, using the free function:
○ free (ptr);
■ where ptr is a pointer to a memory block, which has already been created by
malloc or calloc.
● realloc
○ If the previously allocated memory (by malloc or calloc) is not sufficient and we need
additional space for more elements, we can increase the memory size using realloc
function.
○ Also, if we have allocated a large space and we do not need that much memory, we can
reduce the size by realloc function.
○ Usage:

S3 CT, GPTC Cherthala Programming in C, Module 3 5


■ ptr = malloc(size); // allocation by malloc

ptr = realloc(ptr, newsize);
This function allocates a new memory space of size newsize to the pointer
variable ptr and returns a pointer to the first byte of the new memory block.
● The new area may or may not be at the same place as the old area. But the old data will
be available in the new area also.
● If the reallocation is unsuccessful, the function will return NULL.
● Program to create an integer array dynamically for n elements, read and print them by
using pointers and find the sum of those elements.
#include<stdio.h>
#include<stdlib.h>
void main()
{
int *a,i,n, sum=0;
printf("Enter the number of elements: ");
scanf("%d", &n);
a = (int*) calloc(n, sizeof(int));
if (a==NULL)
{
printf("Error in allocating memory\n");
return;
}

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


{
scanf("%d", &a[i]);
sum = sum + a[i];
}
printf("The elements are: ");
for(i=0; i<n; i++)
{
printf("%d ", a[i]);
}
printf("\nThe sum of these elements is: %d \n", sum);

free(a);
}

● The output will be


Enter the number of elements: 3
3
4
5
The elements are: 3 4 5
The sum of these elements is: 12

S3 CT, GPTC Cherthala Programming in C, Module 3 6


Arrays and Pointers
● When an array is declared with a size, that amount of contiguous memory locations are
reserved and the name of the array is set to the first element of the array. Thus the array name
itself is a pointer to the first element of the array.
● For example, if we initialize an array,
○ int arr[5]={10, 20, 30, 40, 50};
○ Here arr is the array name and it is the pointer to the first element, ie, 10.
○ This means arr is the address of the element arr[0].
Array notation for Equivalent pointer Array notation Equivalent pointer
values notation for address notation

arr[0] *(arr) &arr[0] arr

arr[1] *(arr+1) &arr[1] arr+1

arr[2] *(arr+2) &arr[2] arr+2

arr[3] *(arr+3) &arr[3] arr+3

arr[4] *(arr+4) &arr[4] arr+4


● Program to read and print an array of n elements using pointers only.
#include<stdio.h>
void main()
{
int a[10],i,n;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements: \n");
for(i=0; i<n; i++)
{
scanf("%d", (a+i));
}
printf("The elements are: ");
for(i=0; i<n; i++)
{
printf("%d \n", *(a+i));
}
}
● Multidimensional arrays also can be represented by using pointers.
● For example, consider a 2-dimensional array p[7][6], the jth element in the ith row can be
represented as *(*(p+i)+j) .
● Here p+i represents the pointer to the ith row and *(p+i) + j represents the jth element in the
(p+i)th row.
● This element can be printed using *(*(p+i)+j).

S3 CT, GPTC Cherthala Programming in C, Module 3 7


● Program to read and print a matrix using pointers only.
#include<stdio.h>
void main()
{
int a[10][10],i,j,m=3,n=2;
printf("Enter the elements: \n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", *(a+i)+j);
}
}
printf("The matrix is: \n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%d \t", *(*(a+i)+j) );
}
printf("\n");
}
}

S3 CT, GPTC Cherthala Programming in C, Module 3 8


Strings and Pointers
● A character array initialized as follows;
char str[5] = “good”;
● This can also be initialized by a character pointer as follows;
char *str = “good”;
● This will also add ‘\0’ at the end. The pointer str points to the first character of the array.

● We can point many pointers to a string as follows.


char *str = “good”;
char *str2, *str3, *str4;
str2 = str;
str3 = str2;
str4 = str;
● All will point to the same string str.
● But if we read the string from outside the program (say, from the keyboard), the pointer should
be declared as an array with size, otherwise it will cause segmentation fault.

Array of Pointers
● The main use of an array of pointers is the handling of a table of strings such as all students
in a class.
● The normal initialization of a 2-dimensional character array for such a purpose is given below.
char name[3][10] = {“New Zealand”, Australia”, “India” };
● This can be done by array of pointers as
char *name[3] = {“New Zealand”, Australia”, “India” };
○ Here name is an array of three pointers where each pointer points to a particular string.

● The character arrays with the rows of varying length are called ragged arrays and are better
handled by pointers.

********************************************

S3 CT, GPTC Cherthala Programming in C, Module 3 9


Questions from Module III

Nov 2022
1. ...........is a variable that can hold the memory address of another variable. (1)
2. Write the syntax of malloc() (1)
3. What is Call by Reference? Give an example. (3)
4. Write advantages of dynamic memory allocation. (3)
5. How to access the elements of an array using pointers? (3)
6. How to initialize a string using pointers? (3)
7. Write a C program to sort a single dimensional array of size ‘10’ in ascending order using
pointer to array. (7)
8. Explain the use of pointers to arrays with an example. (7)

Nov 2023
1. ...........function used to dynamically deallocate a memory. (1)
2. Write the syntax of declaring a pointer variable. (1)
3. Illustrate the method of passing pointers to a function with an example. (3)
4. Define pointer. What are the advantages of pointers in C? (3)
5. Write the output of the following code. (3)
#include<stdio.h>
int main(){
int a[5]={1,2,3,4,5};
int *p;
p=a;
for(int i=0;i<5;i++) {
printf("\n%x",*p);
p++; }
return 0; }
6. Write a short note on array of pointers. (3)
7. Explain any two pointer arithmetic operations with examples. (3)
8. Compare malloc() and calloc(). (4)
9. Write a C Program to find the sum of two matrices using pointers. (7)

S3 CT, GPTC Cherthala Programming in C, Module 3 10

You might also like