-9

I found this piece of code on internet. How does this initialize the array?

char words[][MAXLENGTH] =
{
    "india",
    "pakistan",
    "nepal",
    "malaysia",
    "philippines",
    "australia",
    "iran",
    "ethiopia",
    "oman",
    "indonesia"
};
Biffen
  • 6,249
  • 6
  • 28
  • 36
Faizan
  • 3
  • 2

2 Answers2

1

The given array is an array of strings. Each index of words is a string.

e.g:

words[0] = "india"
words[1] = "pakistan"
and so on.

You can use words[0][j] to refer to the characters present in india, words[1][j] for referring to characters of pakistan.

Maybe the following code will help you visualize the array:

#include <iostream>

int main() {
    int MAXLENGTH = 10;
    char words[][MAXLENGTH] =
    {
        "india",
        "pakistan",
        "nepal",
        "malaysia",
        "philippines",
        "australia",
        "iran",
        "ethiopia",
        "oman",
        "indonesia"
    };

    for(int i=0;i<MAXLENGTH;i++)
    {
        std::string s = words[i];
        for(int j=0;j<s.size();j++)
        {
            std::cout << words[i][j] << " ";
        }
        std::cout << "\n";
    }
    return 0;
}
Abhishek Keshri
  • 3,074
  • 14
  • 31
0

char words[][MAXLENGTH] Initialises a 2D array of characters. Basically defines an array of elements and each element in the array is an array of characters e.g. "india"

MAXLENGTH Defines the maximum length of each word in the words array.

char singleWord[] = {"india"} -> an array of characters, meaning by calling singleWord[0] the character i would be returned.

By calling words[2] the character array "nepal" would be returned.

I'm not sure exactly what kind of answer you were looking for, but if you have any questions let me know.