Reputation: 509
Currently, I have working code that reads like this:
char input[4][10] = {ARR1, ARR2, ARR3, ARR4};
Clearly, I am creating a 2d array with these 1d arrays, which are constants defined elsewhere. However, I need to change this code so that it reads the names of the desired 1d arrays from a file and initializes the 2d array accordingly.
For example, if the file contained:
ARR9 ARR3 ARR5 ARR7
Then the initialization would run like (assume all these arrays are all defined):
char input[4][10] = {ARR9, ARR3, ARR5, ARR7};
I have no problem reading from the file but am having difficulties with creating the 2d array and with using a value read from the file as a name of an array.
Upvotes: 2
Views: 124
Reputation: 153348
Let's say the "constants defined elsewhere" presently look like this
const char *ARR1 = "Alpha";
const char *ARR2 = "Bravo";
const char *ARR3 = "Charlie";
Solution 1
const char *ARR_Value[] = "Alpha", "Bravo", "Charlie", 0;
const char *ARR_Name[] = "ARR1", "ARR2", "ARR3", 0;
// Pseudo code
Read file keyword
find matching ARR_Name[]
apply corresponding ARR_Value[] to input[]
A more elegant solution
typedef struct {
const char *Name;
const char *Value;
} ARR_t;
const ARR_t ARR[] = {
{ "ARR1", "Alpha"},
{ "ARR2", "Bravo"},
{ "ARR3", "Charlie"},
{ 0, 0}
};
// Pseudo code
Read file keyword
find matching ARR[] by doing strcmp(keyword, ARR[i].Name)
apply corresponding ARR[i].Value to input[]
Not clear if OP needs to initialize and then change input[] contents or not as the post is char input[4][10]
and not const char input[4][10]
.
Upvotes: 0
Reputation: 409166
C doesn't have introspection or reflection, so it's not really possible that way.
You can however have a translation table, that translates from the strings "ARR1"
, "ARR2"
etc., to the actual arrays, and then you can copy the contents from the actual array to the input
entry. Or instead of having an array of array like you have now, you can have an array of pointers and just set the pointers to point to the correct array.
Upvotes: 2