C PRGM Unit9
C PRGM Unit9
C- Programming
Unit 9: Pointers
Syllabus Unit: - 9
Fundamentals
As you know, variable is a data name that may be used to store a data value. A variable
refers to a memory location that can store only one value at a time but can very throughout the
program.
Example: -
Int num=10;
So, every variable is a memory location and every memory location have its address defined
which can be accessed using ampersand (&) operator, which denotes an address in memory.
Consider the following example,
#include <stdio.h>
int main () {
int var1;
char var2[10];
return 0;
}
Teksan Gharti
BE SEM - I
C- Programming
Output
Pointer: -
A pointer is a special variable that stores the address of another variable., i.e., address of the
memory location. Unlike other variables that hold values of a certain type, pointer holds the
address of a variable. For example, an integer variable holds an integer value, however an
integer pointer holds the address of an integer variable. Example….
Here, the pointer p stores the address of variable having name var.
Features of pointer.
• Normal variable stores the value whereas pointer variable stores the address of the
variable.
• The content of the C pointer always be a whole number i.e. address.
• Always C pointer is initialized to null, i.e. int *p = null.
• The value of null pointer is 0.
• & symbol is used to get the address of the variable.
• symbol is used to get the value of the variable that the pointer is pointing to.
• If a pointer in C is assigned to NULL, it means it is pointing to nothing.
• Two pointers can be subtracted to know how many elements are available between
these two pointers.
• But, Pointer addition, multiplication, division are not allowed.
• The size of any pointer is 2 bytes (for 16-bit compiler).
Pointer Declaration: -
Like any variable or constant, you must declare a pointer before using it to store any variable
address. The general form of a pointer variable declaration is –
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name
of the pointer variable. The asterisk * used to declare a pointer.
Teksan Gharti
BE SEM - I
C- Programming
Here, “int” is the data type and “A” is the name of pointer and * is used to denote that “A”
is pointer variable and not a normal variable.
Initialize a pointer
After declaring a pointer, we initialize it like standard variables with a variable address. To get
the address of a variable, we use the ampersand (&) operator, placed before the name of a
variable whose address we need.
pointer = &variable;
Program:-
#include <stdio.h>
int main()
{
int a=10; //variable declaration
int *p; //pointer variable declaration
p=&a; //store address of variable a in pointer p
printf("Address stored in a variable p is:%x\n",p); //accessing the address
printf("Value stored in a variable p is:%d\n",*p); //accessing the value
return 0;
}
Output:
Teksan Gharti
BE SEM - I
C- Programming
Passing pointer to function: -
Just like any other argument, pointers can also be passed to a function as an
argument. When we pass a pointer as an argument instead of a variable then the address of the
variable is passed instead of the value. So any change made by the function using the pointer
is permanently made at the address of passed variable. This technique is known as call by
reference in C.
Syntax:-
Here, &orginal_var1 is passed as argument during calling the function fname , which is address
of orginal_var1 and * var is passed as argument in function fname function.
Simple program: -
#include <stdio.h>
int main()
{
int* p, i = 10;
p = &i;
addOne(p);
printf("%d", *p); // 11
return 0;
}
Output: -
Teksan Gharti
BE SEM - I
C- Programming
Program to swap two number using concept “passing pointer as argument in function”.
#include <stdio.h>
void swapnum(int *num1, int *num2)
{
int tempnum;
tempnum = *num1;
*num1 = *num2;
*num2 = tempnum;
}
int main( )
{
int v1 = 11, v2 = 77 ;
printf("Before swapping:");
printf("\nValue of v1 is: %d", v1);
printf("\nValue of v2 is: %d", v2);
printf("\nAfter swapping:");
printf("\nValue of v1 is: %d", v1);
printf("\nValue of v2 is: %d", v2);
}
Output: -
Teksan Gharti
BE SEM - I
C- Programming
Program to add the all values in the array using concept “passing pointer as argument
in function”.
#include<stdio.h>
Output: -
Teksan Gharti
BE SEM - I
C- Programming
Relationship between Arrays and pointer
As we know that array is a collection of items of similar data types. And the items in an array
are stored in contagious memory locations in computers memory heap. Now consider the array
is declared as follows……
int a[5];
Now in above declaration of the array, if the first element of array a[0] is stored at memory
location 0x16 (say) then the second element a[1] of array will be stored at the memory location
adjacent to it which is 0x16 as integer occupies 4 bytes of memory.
In C programming, the name of an array always points to the base address i.e.
above “a” will refer to the address 0x12. So &a[0] and ‘a’ are equal. That is why arrays and
pointers are analogous in many ways.
int *p;
int a[5];
p = a;
Now in above declaration &a[0] is equivalent to pointer variable p and a[0] is equivalent to *p
&a[1] is equivalent to p+1 and a[1] is equivalent to *p+1……
*p == a[ 0 ]; //same value
*(p + 2) == a[ 2 ]; //same value
Teksan Gharti
BE SEM - I
C- Programming
So, in general,
1) Arrays and pointers are intimately related in C and often may be used interchangeably.
2) An array name can be thought of as a constant pointer.
3) Pointers can be used to do any operation involving array subscripting.
#include <stdio.h>
int main()
{
int i, x[2], sum = 0;
int *p;
p = x; //assign the base address
Output:-
Teksan Gharti
BE SEM - I
C- Programming
Dynamic memory allocation
As you know, an array is a collection of a fixed number of values. Once the size of an array is
declared, you cannot change it.
Consider the following example….
Array length=5
First index=0
Last index=4
As it can be seen that the length (size) of the array above made is 5. But what if there is a
requirement to change this length (size). For Example,
If there is a situation where only 3 elements are needed to be entered in this array. In this case,
the remaining 2 indices are just wasting memory in this array. So there is a requirement to
lessen the length (size) of the array from 5 to 3.
Take another situation. In this, there is an array of 5 elements with all 5 indices filled. But there
is a need to enter 3 more elements in this array. In this case 3 indices more are required. So the
length (size) of the array needs to be changed from 5 to 8.
So to solve this issue, you can allocate memory manually during run-time. This is known as
dynamic memory allocation in C programming.
Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of
a data structure (like Array) is changed during the runtime or it is an aspect of allocating and
freeing memory according to your needs.
Dynamic memory is managed and served with pointers that point to the newly allocated space
of memory in an area which we call the heap. Now you can create and destroy an array of
elements at runtime without any problems.
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. They are:
1) malloc()
2) calloc()
3) free()
4) realloc()
Teksan Gharti
BE SEM - I
C- Programming
1) malloc()
“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.
malloc tries to allocate a given number of bytes and returns a pointer to the first address
of the allocated region. If malloc fails then a NULL pointer is returned. malloc doesn't
initialize the allocated memory and reading them without initialization invokes undefined
behaviour.
Syntax:
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(5 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 20 bytes of memory. And,
the pointer ptr holds the address of the first byte in the allocated memory.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
printf("Please Enter the Size of pointer that you want to allocate : ");
scanf("%d", &n);
Teksan Gharti
BE SEM - I
C- Programming
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else
{
return 0;
}
Output: -
Teksan Gharti
BE SEM - I
C- Programming
2) calloc()
The calloc function stands for contiguous allocation. This function is used to allocate
multiple blocks of memory. It is a dynamic memory allocation function which is used to
allocate the memory to complex data structures such as arrays and structures.
Malloc function is used to allocate a single block of memory space while the calloc function is
used to allocate multiple blocks of memory space. Each block allocated by the calloc function
is of the same size.
Syntax:
For Example:
This statement allocates contiguous space in memory for 20 elements each with the size of the
int i.e 4..
#include <stdio.h>
int main()
{
int i, * ptr, sum = 0;
int n;
printf("Please Enter the Size of pointer that you want to allocate : ");
scanf("%d", &n);
if (ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
Teksan Gharti
BE SEM - I
C- Programming
printf("Calculating the sequence sum of the first n terms \ n ");
for (i = 0; i < 10; ++i)
{
*(ptr + i) = i;
sum += *(ptr + i);
}
Output: -
The calloc function is generally more suitable and efficient than that of the malloc function.
While both the functions are used to allocate memory space, calloc can allocate multiple blocks
at a single time. You don't have to request for a memory block every time. The calloc function
is used in complex data structures which require larger memory space.
The memory block allocated by a calloc function is always initialized to zero while in malloc
it always contains a garbage value.
3) realloc()
“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.
Syntax:-
Teksan Gharti
BE SEM - I
C- Programming
Program:- Dynamically reallocate the memory which is already allocated by using calloc.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
n = 5;
printf("Enter number of elements: %d\n", n);
Teksan Gharti
BE SEM - I
C- Programming
ptr[i] = i + 1;
}
free(ptr);
}
return 0;
}
Output: -
For example:
#include <stdio.h>
int main()
{
int* ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL)
{
*(ptr + 2) = 50;
printf("Value of the 2nd integer is %d",*(ptr + 2));
}
free(ptr);
}
Teksan Gharti
BE SEM - I
C- Programming
Output
Teksan Gharti