Alex
Alex

Reputation: 44345

How to select an array of strings in C?

I want to define different arrays of strings in C, which then can be e.g. selected depending on some other value, i.e. like following:

char foo[][10] = {"Snakes", "on", "a", "Plane"};
char bar[][10] = {"Fishes", "in", "a", "Lake"};
char *choice;
if (flag == 1) {
  choice = &foo;
} else if (flag == 2) {
  choice = &bar;
} 
printf("%s%s\n", choice[0] , choice[1]); 

Expected result in case flag is 1:

Snakeson

Expected result in case flag is 2:

Fishesin

But the above code gives a segmentation fault error, while I tried differnt definitions for char, i.e. char* and char**. How to do it right? Is there a good tutorial on this matter, i.e. on pointers, arrays, what foo exactly is in the above example...

Upvotes: 0

Views: 818

Answers (2)

Joni
Joni

Reputation: 111329

With arrays of char you need this:

char foo[][10] = {"Snakes", "on", "a", "Plane"};
char bar[][10] = {"Fishes", "in", "a", "Lake"};
char (*choice)[10];
if (flag == 1) {
    choice = &foo[0];
} else if (flag == 2) {
    choice = &bar[0];
} 
printf("%s%s\n", choice[0] , choice[1]); 

For choice[1] to refer to the correct slot it has to be a pointer to the array element type and initialized to &foo[0] instead of &foo. Although they are the same address they are different data types.


If you want choice to be a pointer to the 2-dim char array, it can be done but you have specify both array dimensions when declaring the pointer and remember to dereference it:

char foo[][10] = {"Snakes", "on", "a", "Plane"};
char bar[][10] = {"Fishes", "in", "a", "Lake"};
char (*choice)[4][10];
if (flag == 1) {
    choice = &foo;
} else if (flag == 2) {
    choice = &bar;
} 
printf("%s%s\n", *choice[0] , *choice[1]); 

Upvotes: 2

unwind
unwind

Reputation: 399919

It's easier if you just use arrays of pointers:

int main(void)
{
  const char *foo[] = { "Snakes", "on", "a", "Plane" };
  const char *bar[] = { "Fishes", "in", "a", "Lake" };
  const int flag = 17;
  const char **choice = (flag == 1) ? foo : bar;

  printf("%s %s\n", choice[0], choice[1]);

  return 0;
}

The above prints

Fishes in

Upvotes: 5

Related Questions