简体   繁体   中英

How to make an array of an arrays of strings?

So, I have three array pointers of strings:

char *list1[3] = {"String 11", "String 12", "String 13"};
char *list2[3] = {"String 21", "String 22", "String 23"};
char *list3[3] = {"String 31", "String 32", "String 33"};

I need to access them based on the user input while running it. For example: If the input is 0, access list1 and so on.I figured I could make an array of these array pointers and it could work. This is what I tried:

char *ArrayList[3] = {*list1, *list2, *list3};

But when I tried to print ArrayList[0], ArrayList[1] and ArrayList[2], it just printed the first element of each list.

What am I doing wrong here?

Your ArrayList should hold pointers to the pointers, and you'll need a loop to print all the columns of a row (otherwise you will always get only the first element of a row):

char *list1[3] = {"String 11", "String 12", "String 13"};
char *list2[3] = {"String 21", "String 22", "String 23"};
char *list3[3] = {"String 31", "String 32", "String 33"};

char **ArrayList[3] = {list1, list2, list3};

int main() {
    for (int r=0;r<3;r++) {
        for (int c=0; c<3; c++) {
            printf("%s ",ArrayList[r][c]);
        }
        printf("\n");
    }
}

Output:

String 11 String 12 String 13 
String 21 String 22 String 23 
String 31 String 32 String 33 

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