Array of pointers to string:C Programming Language

Pointers contain addresses of the particular variable that we need. An array of pointers stores the addresses of all the elements of the array and an array of string pointers stores the addresses of the strings present in the array. The array contains the base address of every String element in the array. Here is an example to illustrate this:

char *arr[]={
            "tree",
            "bowl",
            "hat",
            "mice",
            "toon"
          };

This array stores the array base address of “tree” in arr[0]. Similarly the base address of “bowl” in arr[1] and so on. There are many advantages to using a string pointer array over a string array. These are as follows:

  • It occupies less space in the memory: Compared to a string array, an array of pointers to string occupies less space. This means effective use of memory space because if we create a 2D array then we have to create an array with column count atleast equal to the longest String and it leads to a lot of space wastage in the array elements with smaller value.
  • Manipulation of strings: An array of pointers to string allows greater ease in manipulating strings and performing different operations on strings.

Program to arrange the string array alphabetically and display the result

The following program compares the strings in the pointer array, arranges them alphabetically and shows its result. It uses an array of pointers to string to store the values and perform operations:

In this we have used bubble sorting(you can use any of your choice and make a custom implementation).

#include <stdio.h>
#include <String.h>
int main()
{
	//initializing the pointer string array
    char *names[]={
                    "tree",
                    "bowl",
                    "hat",
                    "mice",
                    "toon"
                    };
    char *temp;//temporary variable for swaping the values
    int i,j,a;
    printf("The names are:\n");
    for(i=0 ;i<5 ;i++ )
        printf("%s\n",names[i]);
    //arranging names in alphabetically using selection sort
    for(i=0 ;i<5 ;i++ ){
        for(j=i+1 ;j<5 ;j++ ){
            a=strcmp(names[i],names[j]);//compares the two string and returns an integer value
			//if the value of a is greater than 0 then swapping begins
            if(a>0){
                temp=names[i];
                names[i]=names[j];
                names[j]=temp;
            }
        }
    }
    printf("The arranged names are:\n");
    for(i=0 ;i<5 ;i++ )
        printf("%s\n",names[i]);
    return 0;
}

Output:-
The names are:
tree
bowl
hat
mice
toon
The arranged names are:
bowl
hat
mice
toon
tree

Drawbacks of Array of Pointers to String

The major drawback that we face while using an array of pointers to string is that we cannot take inputs to the string array using scanf() function. For a normal string array, we can either initialize the array with values or take string inputs from the user. But in the case of an array of pointers to string this case does not apply. we can only store values by initializing the array. This is because the memory location contains garbage values and it is not feasible to send garbage values to scanf() function. Thus the user cannot take inputs from the keyboard.

Solution:

We can solve the problem of keyboard inputs to an array of pointers to string by the following method:

#include<stdio.h>
#include<String.h>
#include<stdlib.h>
int main()
{
	char *names[5],a[5];//declaring the string pointer array as well as a char array
	int l,i;
	char *x;
	printf("Enter 5 strings:\n");
	/*taking inputs in char array as well as copying them to the string pointer array*/
	for(i=0 ;i<5 ;i++ )
	{

		scanf("%s",a);//taking values in char array
		l=strlen(a);
		x=(char*)malloc(l+1);//used malloc to allocate dynamic memory. l+1 to store "\0". 
		strcpy(x,a);
		names[i]=x;
	}
        printf("The strings are:\n");
	for(i=0 ;i<5 ;i++ )
		printf("%s\n",names[i]);
	return 0;
}

Output:-
Enter 5 strings:
tree
bowl
hat
mice
toon
The strings are:
tree
bowl
hat
mice
toon

In this process, we first take the string inputs in a character array and then copy it to the string pointer array. Let us understand the process in steps:

  • First, we take string inputs to the variable a[5].
  • As we take the first input the length of the string is calculated using the function strlen() and stored in the variable l. This is done so that we can dynamically allocate memory to the pointer array for storing the strings.
  • In the next step, we allocated memory of the length l+1 (+1 for adding ‘\0’ to the string) using the standard library function malloc(). It requires the size or number of bytes to be reserved in the memory and returns the base address of the memory that is being allocated. The address type returned is void* type because it can be allocated to any sort of data type depending on the user. We also see the presence of (char*). This is used for typecasting the memory address that is allocated by malloc() for storage.
  • In the next step, we copy the base address of the string that we entered into the memory that was allocated by the function malloc().
  • Now we copy that address to the string pointer array that we created.

We see that this process is quite lengthy and inadequate for use. Thus, a string array is usually preferred over a string pointer array. But we must not ignore its many advantages.

An investment in knowledge always pays the best interest. Hope you like the tutorial. Do come back for more because learning paves way for a better understanding.

Do not forget to share and Subscribe.

Happy coding!! :)

 

  • HARSHA

    I have a question :
    If the statement was
    printf(“%d”,”abc”[2]);

    • http://www.codingeek.com Hitesh Garg

      It will simply print “c” as output.
      You can check working example here – http://ideone.com/VXDbWA