ADVERTISEMENT
ADVERTISEMENT

What is array of string in C ?

In C, an array of strings is a data structure that stores a fixed-size sequential collection of strings. Each element in the array is a string, and the size of the array is determined at compile-time.

There are different ways to define an array of strings in C:

  1. Two-dimensional array of characters:
  2. Using Pointers

 Two-dimensional Array of Characters

Here, str is a two-dimensional array of characters where ROWS is the number of rows and COLS is the maximum number of characters in each string. This method is used when the size of the strings is known and fixed.

char str[ROWS][COLS];

Here's an example of an array of strings:

#include <stdio.h>
int main() 
{
   char str[3][100] = { "Tech", "Skill", "Guru" };
   int i;
   for (i = 0; i < 3; i++)
   {
      printf("%s ", str[i]);
   }

   return 0;
}

OUTPUT: Tech Skill Guru

In this example, the array str is declared as a two-dimensional array of characters with 3 rows and 100 columns. Each row of the array represents a string, and the strings are "Tech", "Skill", and "Guru". The for loop is used to iterate through the array and print each string.

Using Pointers

Here, str is an array of pointers to characters where ROWS is the number of strings in the array. This method is used when the size of the strings is not known at compile-time.

char *str[ROWS];

Another way to declare Array of strings is by using array of pointers.

#include <stdio.h>
int main() 
{
   char *str[] = { "Tech", "Skill", "Guru" };
   int i;

   for (i = 0; i < 3; i++)
   {
      printf("%s ", str[i]);
   }

   return 0;
}

This will output the same result as previous example. Here, the array 'str' is an array of pointers to character. Each element of the array 'str' is a pointer to a string.

Disadvantages of using a 2D array of strings in C

  1. Fixed size: The size of a 2D array of strings is fixed at compile-time and cannot be changed at runtime. This means that if more space is needed, a new array must be created and the old one must be discarded.

  2. Memory overhead: Since the size of a 2D array of strings is fixed, it may lead to a significant amount of wasted memory if the actual number of strings is less than the maximum size of the array.

  3. Complexity: A 2D array of strings is a complex data structure that can be difficult to manipulate and understand, especially for large arrays or arrays with a high number of dimensions.

  4. Inefficient use of memory: A 2D array of strings stores all the strings in contiguous memory. If the length of strings are different, it leads to a lot of wasted space.

  5. Limited flexibility: A 2D array of strings is limited in terms of the operations that can be performed on it. It can only be accessed and modified one element at a time.

It's worth noting that these disadvantages are not exclusive to 2D arrays of strings, they also apply to other types of arrays. 


ADVERTISEMENT

ADVERTISEMENT