Ziv Sion
Ziv Sion

Reputation: 454

C get the 2nd char in the 2nd element in array of strings

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"

Upvotes: 0

Views: 471

Answers (1)

anastaciu
anastaciu

Reputation: 23802

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

Upvotes: 1

Related Questions