Home > Net >  C get the 2nd char in the 2nd element in array of strings
C get the 2nd char in the 2nd element in array of strings

Time:05-03

I have an array of strings. How can I get the char "v" from the second element in the array?

char* name = "Ziv";
char* name2 = "Avinoam";
char* name3 = "Matan";

char** stringsArray[3] = { name, name2, name3 };
printf("v is: %c", *(stringsArray[1])[1]); // I want to get "v" from "Avinoam"

CodePudding user response:

The type of stringsArray is not correct, what you have is an array of pointers to pointer to char, you need an array of pointers to char:

char* stringsArray[] = {name, name2, name3};

Indexing is the same as in a 2D array, you could use pointer notation:

printf("v is: %c", *(*(stringsArray   1)   1)); 

But using square brackets is much clearer:

printf("v is: %c", stringsArray[1][1]);

Live sample: https://godbolt.org/z/TMjf1GcE9

  • Related