简体   繁体   中英

About 2d array of character pointers

I found the following declaration in my c Book, can anyone explain it:

    char *dic[][40]={
"atlas", "A volume of maps",
"car", "a vehicle",
"telephone", "a communication device",
"", ""
    }

Here what does the 40 means ie which dimension this is?

This is actually kind of a weird way to initialize the dictionary.

It is a 2D array of char* (zero terminated ( \\0 ) strings).

The dimensions are [rows][columns].

So you have 1 row (determined by the initializer) and 40 columns of strings,

where 8 of them are initialized.

NOTE: Are you sure it isnt char dic[][40] (ie, a list of strings of max-length 40) ?

dic is a two-dimensional array of char* ; its dimensions are 1 x 40.

The 40 is given in the declarator and the 1 is implied by the fact that there is only one array in the initializer. The full initializer would have another set of braces, eg,

char *dic[][40] =
{
    {
        "atlas",     "A volume of maps",
        "car",       "a vehicle",
        "telephone", "a communication device",
         "",         ""
    }
};

With the extra braces, it is clearer that the implicit dimension is 1.

Each element in the two-dimensional array is a pointer of type char* . The first eight pointers are initialized to point to the eight string literals given in the initializer.

I think that there may be error in book, it seems that they wanted dictionary - 3D array:


 char *dic[][40]={
            {"atlas", "A volume of maps"},
            {"car", "a vehicle"},
            {"telephone", "a communication device"},
            {"", ""}
        };

The 40 in your code means the maximum length of characters (or the total length of the string) is 40.

Think char *dic[][40] as an array of pointers. Wherein one pointer points to a maximum of 40 characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM