0

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...

4
  • see man page of printf. You are using it in a very wrong way!try printf("%s%s\n", choice[0] , choice[1]); Commented Jun 24, 2013 at 11:08
  • 3
    compile with warnings (gcc: -Wall) Commented Jun 24, 2013 at 11:09
  • @Maneolin - you are right - I updated the code. But error is still the same (segmentation fault). Commented Jun 24, 2013 at 11:11
  • Thread stackoverflow.com/questions/2003745/… should really help you. Commented Jun 24, 2013 at 11:41

2 Answers 2

5

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

1 Comment

Your suggestion seems to work! I will try it in the actual code.
2

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]); 

Comments

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.