1 of 12

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

2 of 12

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.

  • Syntax:

char variable_name[r] = {list of string};

Here,

  • var_name is the name of the variable in C.
  • r is the maximum number of string values that can be stored in a string array.
  • c is a maximum number of character values that can be stored in each string array.

3 of 12

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;

}

4 of 12

Output

String array Elements are:

Home

Homes

Homesfor

5 of 12

The Representation of the above program

6 of 12

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.

7 of 12

� 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].

8 of 12

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.

  • Syntax:

char *arr[] = { “Home", " Homes", " Homesfor" };

9 of 12

10 of 12

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;

}

11 of 12

Output

String array Elements are:

Home

Homes

Homesfor

12 of 12

Thank you�