How2Lab Logo
tech guide & how tos..

Pointers in C - Part 2 of 9

A pointer can point to data objects of any type, not merely integer or float. Thus one can have a pointer to arrays, structures or even to functions. At this point, it is necessary to emphasize that, when a pointer variable is declared such as in:

int *p; 

Space will not be automatically allocated for an object of type int. C supports a facility to allocate such space as and when it is required. Such dynamic allocation of memory space helps in reducing overall memory requirement for the program. Also as we will see later, such a facility enables us create dynamic data structures such as list, tree, etc., efficiently.

In order to allocate space for the data object pointed to by p, C provides a library function malloc(). The space thus created can be freed using another function free(). Thus C allows you to dynamically allocate space in memory and thereafter free the space once its use is over.

The general syntax for using malloc function is illustrated below:

p = (datatype *) malloc(sizeof(datatype));
p = (int *) malloc(sizeof(int));

If datatype is int, then sizeof(int) will determine the space required to store an integer data, viz. 4 bytes. Thus, in the above example, 4 bytes of integer space will be allocated in the memory and p will be assigned the address of the allocated space, i.e. p will point to the allocated space.

Likewise, if datatype is double, malloc will reserve a space of 8 bytes and will assign the address of this space to p. The sizeof function helps the program to become machine independent. This function always returns a pointer to char type. Hence we need to use the type cast operator (datatype *) to match the type of p.

Pointers and Arrays

It may be recalled that the name of a one dimensional array essentially stores the address of the first element of the array, i.e. it points to the location where the array is stored.

Consider the following array declaration:

int x[20]; 

Here x stores the address of the array, which is essentially the address of the array's first element, viz. &x[0]. The location of any array element, say the ith element of x can be determined in either of the following two ways - &x[i] or (x + i). In (x + i), the integer quantity i (position of a specific (ith) element in the array) is added to the address of the first element to extract the address of the ith element. This is possible because all the elements of the array x, occupy a contiguous block of memory space.

The following example illustrates the usage of pointers to manipulate a one dimensional array:

#include <stdio.h>
	static int x[5] = {1, 2, 3, 4, 5};
	int *p;
	int i = 2;

	p = &x[i];   //Assigns p to the address of the third element
	p = (x + i); //This statement is equivalent to p = &x[i]

	x[3] = *p;   //This will assign the value of 3rd element to the 4th element
	*(x + 3)=*p; //This is an alternate way of writing x[3] = *p

Creation of an Array using Pointers

We have already seen that an array name is actually a pointer to the first element of the array. However a conventional array definition results in a fixed block of memory being reserved at the beginning of the program which may lead to wastage of memory space during program execution. This problem can be avoided if an array is implemented using a pointer variable. The use of a pointer variable to represent an array requires some sort of initial memory allocation before the array elements are processed. And we have mentioned earlier that this is done by using the malloc library function.

Compare the following two blocks of statements to understand the difference between conventional array declaration and array implementation using pointers by dynamic memory allocation.

Block 1:
#include <stdio.h>
#define size 10
int arr[size]; 	//Conventional static memory allocation

Block 2:
#include <stdio.h>
#define size 10
int *arr;  //Defines a pointer to an integer variable

	arr = (int *)malloc(size * sizeof(int)); //Dynamic memory allocation

Let us now look at a realistic example that illustrates the usage of a pointer in creating a one-dimensional array of integers and sorting them.

#include <stdio.h>
#include <malloc.h> //Must include this library in order to use the malloc() function

	int i, n, *vector;
	void bubble();

	printf("Size of array? ");
	printf("\nSize of array = %d\n",n);

	vector = (int*) malloc(n*sizeof(int)); //Dynamic memory allocation
	printf("\nEnter array elements separated by blanks\n");

	/* Read the array elements */
	for(i=0; i < n; i++)
		scanf("%d", vector+i);

	/* Display the read elements */
	for(i=0; i < n; i++)  
		printf("%d ", *(vector+i));

	/* Invoke function bubble sort*/ 

	printf("\n Sorted array \n"); 
	for(i=0; i < n; i++)  
		printf("%d \t", vector[i]);

	free(vector); //frees up the allocated memory
} /* end of main() */ 

/* Bubble sort function */
void bubble(int *x, int m)
	int pass, i, temp; 
	for(pass=0; pass < m-1; pass++)
		for(i=0; i < m-pass-1; i++) 
			if(*(x+i) > *(x+i + 1)) 
				/* interchange */
				temp     = *(x+i);
				*(x+i)   = *(x+i + 1); 
				*(x+i+1) = temp; 

Buy Domain & Hosting from a trusted company
Web Services Worldwide | Hostinger
About the Author
Rajeev Kumar
CEO, Computer Solutions
Jamshedpur, India

Rajeev Kumar is the primary author of How2Lab. He is a B.Tech. from IIT Kanpur with several years of experience in IT education and Software development. He has taught a wide spectrum of people including fresh young talents, students of premier engineering colleges & management institutes, and IT professionals.

Rajeev has founded Computer Solutions & Web Services Worldwide. He has hands-on experience of building variety of websites and business applications, that include - SaaS based erp & e-commerce systems, and cloud deployed operations management software for health-care, manufacturing and other industries.

Refer a friendSitemapDisclaimerPrivacy
Copyright © All rights reserved.