Topic: Implementation of Arrays and Strings
B.Sc(HONS) I Sem �Computer Science
(CC): Programming Fundamentals using C
PREPARED BY: Mr. Rabin Kumar Mullick
Department of Computer Science
Date: 22/11/2019
Theory:
In C programming String is a 1-D array of characters and is defined as an array of characters. But an array of strings in C is a two-dimensional array of character types. Each String is terminated with a null character (\0). It is an application of a 2d array.
char variable_name[r] = {list of string};
Here,
Example:
// C Program to print Array
// of strings
#include <stdio.h>
// code
int main()
{
char arr[3][10] = {“Home",
“Homes", “Homesfor"};
printf("String array Elements are:\n");
for (int i = 0; i < 3; i++)
{
printf("%s\n", arr[i]);
}
return 0;
}
Output
String array Elements are:
Home
Homes
Homesfor
The Representation of the above program
We have 3 rows and 10 columns specified in our Array of String but because of prespecifying, the size of the array of strings the space consumption is high. So, to avoid high space consumption in our program we can use an Array of Pointers in C.
� Invalid Operations in Arrays of Strings
We can’t directly change or assign the values to an array of strings in C.
Example:
char arr[3][10] = {“Home", " Homes", " Homesfor"};
Here, arr[0] = “HFH”; // This will give an Error which says assignment to expression with an array type.
To change values we can use strcpy() function in C
strcpy(arr[0],“HFH"); // This will copy the value to the arr[0].
Array of Pointers of Strings�
In C we can use an Array of pointers. Instead of having a 2-Dimensional character array, we can have a single-dimensional array of Pointers. Here pointer to the first character of the string literal is stored.
char *arr[] = { “Home", " Homes", " Homesfor" };
The C program to print an array of pointers:
// C Program to print Array
// of Pointers
#include <stdio.h>
// code
int main()
{
char *arr[] = {“Home", “Homes", “Homesfor"};
printf("String array Elements are:\n");
for (int i = 0; i < 3; i++)
{
printf("%s\n", arr[i]);
}
return 0;
}
Output
String array Elements are:
Home
Homes
Homesfor
Thank you�