Follow these steps to ensure that the pointer is not NULL and is pointing to a memory address by making use of assertions:
- Define an array containing a number of integers whose average is to be computed:
int arr[]={3,9,1,6,2};
- Set a pointer to point to the array:
ptr=arr;
- Define a function for calculating the average of the array elements. A pointer to an array and the count of the number of values in the array are both passed to this function:
average=findaverage(ptr, count);
- In the function, define an assert expression that ensures that the pointer is not NULL. If the pointer is NULL, the program will display an error and will be aborted:
assert(Ptr != NULL && "Pointer is not pointing to any array");
- If the pointer is not NULL, the array elements will be accessed through the pointer and their average will be computed and displayed on the screen:
for(i=0;i<Count;i++)
{
sum+=*Ptr;
Ptr++;
}
Average=(float)sum/Count;
The program for implementing a validation that ensures the pointer is not NULL and is pointing to a memory address is shown as follows:
// assertprog.c
#include <stdio.h>
#include <assert.h>
float findaverage(int *Ptr, int Count);
int main()
{
int arr[]={3,9,1,6,2};
float average;
int *ptr=NULL,count;
ptr=arr;
count=5;
average=findaverage(ptr, count);
printf("Average of values is %f\n", average);
return(0);
}
float findaverage(int *Ptr, int Count)
{
int sum,i;
float Average;
assert(Ptr != NULL && "Pointer is not pointing to any array");
sum=0;
for(i=0;i<Count;i++)
{
sum+=*Ptr;
Ptr++;
}
Average=(float)sum/Count;
return(Average);
}
Now, let's go behind the scenes to understand the code better.