Unit 3
Unit 3
Declaring a Pointer
Like variables, pointers in C programming have to be declared before they can be
used in your program. Pointers can be named anything you want as long as they
obey C’s naming rules. A pointer declaration has the following form.
data_type * pointer_variable_name;
Here,
Types of Pointers
There are majorly four types of pointers, they are:
Null Pointer
Void Pointer
Wild Pointer
Dangling Pointer
Null Pointer
We can create a null pointer by assigning null value during the pointer declaration.
This method is useful when you do not have any address assigned to the pointer. A
null pointer always contains value 0.
Following program illustrates the use of a null pointer:
#include <stdio.h>
int main()
{
int *p = NULL; //null pointer
printf(“The value inside variable p is:\n%x”,p);
return 0;
}
Output:
The value inside variable p is:
0
Void Pointer
Addition:
In C Programming Language, When a pointer is added with a value, then the value is
first multiplied by the size of the data type and then added to the pointer.
Subtraction:
In C Programming Language, When a pointer is subtracted with a value, then the
value is first multiplied by the size of the data type and then subtracted from the
pointer.
#include <stdio.h>
int main()
{
Output:
Arrays are closely related to pointers in C programming but the important difference
between them is that, a pointer variable takes different addresses as value whereas, in
case of array it is fixed.
#include <stdio.h>
int main()
{
char charArr[4]; int i;
for(i = 0; i < 4; ++i)
{
int arr[4];
In C programming, name of the array always points to address of the first
element of an array.
In the above example, arr and &arr[0] points to the address of the first element.
&arr[0] is equivalent to arr .Since, the addresses of both are the same, the values
of arr and &arr[0] are also the same.
arr[0] is equivalent to *arr (value of an address of the pointer)
Similarly,
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).
In C, you can declare an array and can use pointer to alter the data of an array.
Example: Program to find the sum of six numbers with arrays and pointers
#include <stdio.h> int main()
{
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));
// *(classes + i) is equivalent to classes[i]
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.
Application of array of pointers
Assume that we are going to build an embedded system which uses a different kind
of sensors to measure the temperature.
In this case, we can use an array of pointers to hold the memory address of each
sensor so that it will be very easy to manipulate the sensor status.
Example
sensor[0] will hold the address of the 1st sensor.
sensor[1] will hold the address of the second sensor and so on.
Since it is an array, we can directly interact with the particular sensor using array
index.
we can get the temperature status of 1st sensor using sensor[0], 2nd sensor status
using sensor[1] and so on.
Pointer to pointer
We can also store the address of another pointer in c.
Example
printf("Address of a = %p\n",&a);
printf("ptr is pointing to the address = %p\n",ptr);
printf("dptr is pointing to the address = %p\n",dptr);
printf("Value of a = %d\n",a);
printf("*ptr = %d\n",*ptr);
printf("**dptr = %d\n",**dptr);
return 0;
}
*ptr -> *1024 -> value stored at the memory 1024 is 10 ->10
For example, in the above figure we have a function add() to add two integer
numbers. Here, the function name points to the address of the function itself so we
are using a function pointer fptr that stores the address of beginning of the
function add(a, b) that in 1001 in this case.
Before using a function pointer we need to declare them to tell the compiler the
type of function a pointer can point. The general syntax of a function pointer is,
Syntax of Function Pointer in C
return_type (* pointer_name) (datatype_arg_1, datatype_arg_1, ...);
Declaring a function pointer in C is comparable to declaring a function except
that when a function pointer is declared, we prefix its name which is an
Asterisk * symbol.
For example, if a function has the declaration
float foo (int, int);
Declaration of a function pointer in C for the function foo will be
// function pointer declaration
float (*foo_pointer) (int, int);
int main() {
int a, b;
float (*operation[4])(int, int);
operation[0] = add;
operation[1] = subtract;
operation[2] = multiply;
operation[3] = divide;
printf("Enter two values ");
scanf("%d%d", &a, &b);
Failed to protect memory addresses (locations) - Since pointer can access direct
memory so memory cannot be protected.
Extra care should be taken when function is used to return pointers because local
variables don't live outside function scope and if they are returned as pointers from
function then that pointer will point to nothing when function terminates.
For example,
#include<stdio.h>
int* increment(int a) {
int *b;
*b = a;
*b += 1; // incrementing the value
return b; // returning pointer from the function
}
int main() {
int num = 5;
int *b = increment(num);
St. Joseph’s College of Engineering Page 22
printf("Incremented value = %d", *b);
return 0;
}
In this case, the compiler throws segmentation fault error because you are
returning a copy of a pointer to a local variable. However, that local variable is de-
allocated when the function increment finishes, so when we try to access it
afterwards compiler is not able to reference the pointer.
Safe ways to return a pointer from a function
Return variables are either created using the keyword static or created
dynamically at run time because such variables exist in memory beyond the scope
of the called function.
Use arguments that are passed by their reference because such functions exist in
the calling function scope.
Example: Passing and returning values from functions using pointer in C
#include<stdio.h>
int *larger(int *, int *);
int main() {
int a = 10, b = 15;
int *greater;
// passing address of variables to function
greater = larger(&a, &b);
printf("Larger value = %d", *greater);
return 0;
}
// Passing
parameters func(x,
y);
printf("In main, x = %d y = %d\n", x,
y); return 0;
}
Output:
int main(void)
{
int a = 10, b = 20;
// passing
parameters
swapnum(&a, &b);
printf("a is %d and b is %d\n", a,
b); return 0;
}
Output:
a is 20 and b is 10
Swapping of two numbers
#include <stdio.h>
int main()
{
int x, y, temp;
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
//Swap function definition
void swap(int *a, int *b)
{
int t;
t = *b;
*b = *a;
#include <stdio.h>
int main()
printf("%s \n",str[i]);
}
return 0;
}
Output
Hello World
Mumbai
New Delhi
Program to sort names in alphabetical order using the concept of array of pointers
#include <stdio.h>
#include<string.h>
int main()
{
char *str[6]={"New Delhi","Gujarat","Assam","Chennai","Bangalore","Kerala"},*t;
int i,j,r;
printf("\nBefore Sorting\n");
for(i=0;i<6;i++)
{
printf("%s\n",str[i]);
}
for(i=0;i<6;i++)
{
for(j=i+1;j<5;j++)
{
r=strcmp(str[i],str[j]);
if(r>0)
{
t=str[i];
str[i]=str[j];
str[j]=t;
}
}
}
printf("\nAfter Sorting\n");
for(i=0;i<6;i++)
{
printf("%s \n",str[i]);
After Sorting
Assam
Bangalore
Chennai
Gujarat
Kerala
New Delhi