An Array of Strings in CAn Array is the simplest Data Structure in C that stores homogeneous data in contiguous memory locations. If we want to create an Array, we declare the Data type and give elements into it: Output: 1 2 4 2 4 In C, a Character and a String are separate data types, unlike other programming languages like Python. A String is a collection of Characters. Hence, to define a String, we use a Character Array: Output: Enter a String: Hello Hello Now, we want to create an Array of Strings which means we are trying to create an Array of Character Arrays. We have two ways we can do this:
Using Two-dimensional Arrays:Creating a String Array is one of the applications of two-dimensional Arrays. To get a picture of the arrangement, observe the below representation: For suppose we want to create an Array of 3 Strings of size 5: Every String in a String Array must terminate with a null Character. It is the property of a String in C. Syntax to create a 2D Array: Syntax to create a String Array: Now, let us create an example String Array:
Output: String Array: Black Blame Block
Output: [Error] assignment to expression with Array type
Output: String Array: Hello Blame Block The Disadvantage of using 2D Arrays: Suppose we want to store 4 Strings in an Array: {"Java", "T", "point", "JavaTpoint"}. We will store the Strings like this:
Using Pointers:By using Pointers, we can avoid the Disadvantage of Memory wastage. But how do we do this? We need to create an Array of Pointers pointing to Strings. Hence, we need to create an Array of type "char*". This way, all the Strings are stored elsewhere in the exactly needed memory, and the Pointers in the Array point to those memory locations causing no memory wastage. More specifically, the Pointers in the Array point to the first Character of the Strings. Syntax to create an Array of Pointers: Data Type* name[] = {"Value 1", "Value 2"…}; Syntax to create an Array of String Pointers: char* Array[] = {"String 1", "String 2"…}; Representation: Now, let us create an example String Array: Output: String Array: HI UP AT Summary:We cannot create a String Array like a normal one, as a String is an Array of Characters. We have two ways to do this: 1. Using a Two-Dimensional Array: The Disadvantage of using this way is "Memory wastage," as the memory allocated to every String in the Array will be the memory required to store the longest String of the Array. 2. Using Pointers: Using Pointers, we create a single-dimensional Array of Pointers pointing to Strings. Following this method can eliminate the "Memory wastage" Disadvantage. Next TopicPeak element in the Array in C |