0

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?

2
  • *list1 is equivalent to list1[0]. Commented Sep 23, 2018 at 21:26
  • @melpomene so how do I get the whole list1? Commented Sep 23, 2018 at 21:32

1 Answer 1

2

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 
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, I see. Can you link me a good article explaining pointers and double pointers? I'm still confused as to how you were able to use ArrayList[r][c] for a 1D array. I'm guessing it's because of the double pointer?
It is often more clear to use a non-square 2D like array. Perhaps 2x3 or 3x4 to hep clearly differentiate the role of [r] and [c].
Is there anyway to get list1 from ArrayList and pass it to a function? I've been trying that but keep getting segmentation fault. @chux

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.