Movatterモバイル変換


[0]ホーム

URL:


OverIQ.com

  1. Home
  2. C Programming Tutorial
  3. Array of Strings in C

Array of Strings in C

Last updated on July 27, 2020


What is an Array of Strings?#

A string is a 1-D array of characters, so an array of strings is a 2-D array of characters. Just like we can create a 2-D array ofint,float etc; we can also create a 2-D array of character or array of strings. Here is how we can declare a 2-D array of characters.

12345
charch_arr[3][10]={{'s','p','i','k','e','\0'},{'t','o','m','\0'},{'j','e','r','r','y','\0'}};

It is important to end each 1-D array by the null character, otherwise, it will be just an array of characters. We can't use them as strings.

Declaring an array of strings this way is rather tedious, that's why C provides an alternative syntax to achieve the same thing. This above initialization is equivalent to:

12345
charch_arr[3][10]={"spike","tom","jerry"};

The first subscript of the array i.e3 denotes the number of strings in the array and the second subscript denotes the maximum length of the string. Recall the that in C, each character occupies1 byte of data, so when the compiler sees the above statement it allocates30 bytes (3*10) of memory.

We already know that the name of an array is a pointer to the 0th element of the array. Can you guess the type ofch_arr?

Thech_arr is a pointer to an array of10 characters orint(*)[10].

Therefore, ifch_arr points to address1000 thench_arr + 1 will point to address1010.

From this, we can conclude that:

ch_arr + 0 points to the 0th string or 0th 1-D array.
ch_arr + 1 points to the 1st string or 1st 1-D array.
ch_arr + 2 points to the 2nd string or 2nd 1-D array.

In general,ch_arr + i points to the ith string or ith 1-D array.

We know that when we dereference a pointer to an array, we get the base address of the array. So, on dereferencingch_arr + i we get the base address of the 0th 1-D array.

From this we can conclude that:

*(ch_arr + 0) + 0 points to the 0th character of 0th 1-D array (i.es)
*(ch_arr + 0) + 1 points to the 1st character of 0th 1-D array (i.ep)
*(ch_arr + 1) + 2 points to the 2nd character of 1st 1-D array (i.em)

In general, we can say that:*(ch_arr + i) + j points to the jth character of ith 1-D array.

Note that the base type of*(ch_arr + i) + j is a pointer tochar or(char*), while the base type ofch_arr + i is array of 10 characters orint(*)[10].

To get the element at jth position of ith 1-D array just dereference the whole expression*(ch_arr + i) + j.

*(*(ch_arr+i)+j)

We have learned in chapter Pointers and 2-D arrays that in a 2-D array the pointer notation is equivalent to subscript notation. So the above expression can be written as follows:

ch_arr[i][j]

The following program demonstrates how to print an array of strings.

 1 2 3 4 5 6 7 8 910111213141516171819202122
#include<stdio.h>intmain(){inti;charch_arr[3][10]={"spike","tom","jerry"};printf("1st way\n\n");for(i=0;i<3;i++){printf("string = %s\t address = %u\n",ch_arr+i,ch_arr+i);}// signal to operating system program ran finereturn0;}

Expected Output:

123
string = spike address = 2686736string = tom address = 2686746string = jerry address = 2686756

Some invalid operation on an Array of string#

12345
charch_arr[3][10]={{'s','p','i','k','e','\0'},{'t','o','m','\0'},{'j','e','r','r','y','\0'}};

It allocates30 bytes of memory. The compiler will do the same thing even if we don't initialize the elements of the array at the time of declaration.

We already know that the name of an array is a constant pointer so the following operations are invalid.

12
ch_arr[0]="tyke";// invalidch_arr[1]="dragon";// invalid

Here we are trying to assign a string literal (a pointer) to a constant pointer which is obviously not possible.

To assign a new string toch_arr use the following methods.

12
strcpy(ch_arr[0],"type");// validscanf(ch_arr[0],"type");// valid

Let's conclude this chapter by creating another simple program.

This program asks the user to enter a username. If the username entered is one of the names in the master list then the user is allowed to calculate the factorial of a number. Otherwise, an error message is displayed.

 1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
#include<stdio.h>#include<string.h>intfactorial(int);intmain(){inti,found=0,n;charmaster_list[5][20]={"admin","tom","bob","tim","jim"},name[10];printf("Enter username: ");gets(name);for(i=0;i<5;i++){if(strcmp(name,master_list[i])==0){found=1;break;}}if(found==1){printf("\nWelcome %s !\n",name);printf("\nEnter a number to calculate the factorial: ");scanf("%d",&n);printf("Factorial of %d is %d",n,factorial(n));}else{printf("Error: You are not allowed to run this program.",name);}// signal to operating system program ran finereturn0;}intfactorial(intn){if(n==0){return1;}else{returnn*factorial(n-1);}}

Expected Output: 1st run:

123456
Enter username: adminWelcome admin !Enter a number to calculate the factorial: 4Factorial of 4 is 24

2nd run:

12
Enter username: jackError: You are not allowed to run this program.

How it works:

The program asks the user to enter a name. After the name is entered it compares the entered name with the names in themaster_list array usingstrcmp() function. If match is found thenstrcmp() returns0 and the if conditionstrcmp(name, master_list[i]) == 0 condition becomes true. The variable found is assigned a value of1, which means that the user is allowed to access the program. The program asks the user to enter a number and displays the factorial of a number.

If the name entered is not one of the names in themaster_list array then the program exits by displaying an error message.


Load Comments


C Programming Tutorial

Recent Posts

x

[8]ページ先頭

©2009-2025 Movatter.jp