4

In C, I need to statically pre-allocate an array of numbers, each associated with a different array of strings. Will a code like the following do the trick:

struct number_and_strings {
  int  nnn;
  char **sss;
}

static struct number_and_strings my_list[] = {
  {12, {"apple","banana","peach","apricot","orange",NULL}},
  {34, {"tomato","cucumber",NULL}},
  {5,  {"bread","butter","cheese",NULL}},
  {79, {"water",NULL}}
}
4
  • 2
    Why don't try out and see? Commented Apr 13, 2013 at 16:11
  • 1
    What I fear is that it will seem to work, but due to some misunderstanding of pointers I will end up gulping or leaking memory. Commented Apr 13, 2013 at 16:13
  • The pointers will point at memory locations in the data segment. No leaking there. Commented Apr 13, 2013 at 16:15
  • 1
    No, it will not work. An array is not a pointer, so you can't initialize a pointer to pointer with an initializer for array of string. Commented Apr 13, 2013 at 16:15

1 Answer 1

5

sss is a pointer to pointer. So an array of pointers can't be directly assigned to it. You can assign as follows using compound literals (which is a C99 feature):

static struct number_and_strings my_list[] = {
      {12, (char*[]){"apple","banana","peach","apricot","orange",NULL}},
      {34, (char*[]){"tomato","cucumber",NULL}},
      {5,  (char*[]){"bread","butter","cheese",NULL}},
      {79, (char*[]){"water",NULL}}
    };
Sign up to request clarification or add additional context in comments.

6 Comments

This is not a cast, but something quite different, namely a compound literal. (C jargon and syntax for an unnamed object)
@FreeBud No, AFAIK C89/90 doesn't support it (but gcc supports it as an extension). If you compile in C99 mode, it should be fine. For example, if you are using gcc, then: gcc -std=c99 file.c.
Let me ask that differently: What changes can I put in the struct definition (or other changes), in order for the static array to be declared this way (or similarly), using ANSI C?
@FreeBud What is the compiler that you are you using? First directly copy the struct declaration in my answer and try.
>> What is the compiler that you are you using -- it's tricky. I'm using Digital Mars C on my Windows PC, but the ultimate destination is to be included as part of an Objective C code on an Apple.
|

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.