1

could somedoby clarify some basic C language moments.

struct key {
    char *name;
    int value;
};

struct key first_key_array[] = {
    {"abc", 5},
    {"xyz", 6},
    {"def", 7}
};

struct key second_key_array[] = {
    {"what", 200},
    {"when", 300}
};

struct data {
    struct key **key_array;
};

struct data all_key_arrays[] = {
    {first_key_array},
    {second_key_array}
};

I could directly access first_key_array[0]:

printf("%s %d", first_key_array[0].name, first_key_array[0].value);

But access via all_key_arrays does not work:

printf("%s %d", all_key_arrays[0].key_array[0].name, all_key_arrays[0].key_array[0].value); 

Could somebody share any ideas?

2
  • 4
    The initializer for struct data all_key_arrays[] = is ill-formed. Your compiler should tell you about this. If you don't see any compiler messages then you need to figure out how to stop disabling your compiler's output messages . You need to fix the compiler messages before trying to run the program. Commented Mar 2, 2016 at 21:05
  • 1
    The fix will be that struct key **key_array; should be struct key *key_array;, although this design has a problem that if you go in via all_key_arrays then there is no way of checking you don't access past the end of wherever it is pointing Commented Mar 2, 2016 at 21:06

1 Answer 1

1

Try changing the initializer for all_key_arrays to:

struct data all_key_arrays[] = {
    first_key_array,
    second_key_array
};

or

struct data all_key_arrays[] = {
    &first_key_array[0],
    &second_key_array[0]
};

Explanation -- all_key_arrays is an array pointers, so the values you initialize the array to should be, well, pointers.

Sign up to request clarification or add additional context in comments.

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.