Reputation: 53
I haven't had a chance to try this and my understanding of C is amateur at best. The closest I found to this question was for c++ but dealt with fixed enum values.
Say you have a 2D integer array dynamically allocated like this:
4x4
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
would it be possible to use enum to assign dynamic names to each column and row and then access those rows and columns by their name?
Like:
apples bread carrot dinosaur
apples 0 0 0 0
bread 0 0 0 0
carrot 0 0 0 0
dinosaur 0 0 0 0
Allowing me to do something like this:
matrix[apples][bread] += 1;
EDIT
When I say "dynamic" what I mean is when a value is compiled at run time with no fixed size. So on one run the matrix may be 2x2 or 82x82 and the enum
values could be apple, bear, or apple, bear, teddy etc.
Upvotes: 0
Views: 2577
Reputation: 123468
Yes, you can use enumerations to create symbolic constants for each index:
enum { apples, carrot, bread, dinosaur };
You can also use regular variables:
const int apples = 0;
const int carrot = 1;
const int bread = 2;
const int dinosaur = 3;
You can also use the preprocessor:
#define APPLES 0
#define CARROT 1
#define BREAD 2
#define DINOSAUR 3
What you can't do is create any of these things at runtime. If you decide at runtime to create a 5x5 array, you cannot also create a new symbolic constant (via an enum
or variable or macro). That can only be done at compile time.
EDIT
What you can do is create some kind of associative data structure (map or lookup table) that associates a string with an integer value, and then you can do something like...
Some_Map_Type map;
...
addIndex( map, "apples", 0 );
addIndex( map, "carrot", 1 );
addIndex( map, "bread", 2 );
addIndex( map, "dinosaur", 3 );
...
do_something_with( matrix[getIndex(map, "apples")][getIndex(map, "bread")] );
and then at runtime prompt for a new index name and value, like:
printf( "Gimme a new index: " );
scanf( "%s %d", name, &value ); // doing it this way *just* for brevity - don't actually do it like this
addIndex( map, name, value );
...
do_something_with( matrix[getIndex(map, name)][getIndex(map, "bread")] );
That may or may not be worth the effort for you.
Upvotes: 3
Reputation: 29985
C is a statically typed language and you cannot add variable names to your program at runtime. This includes enums too. A hash table like std::map
may be used for your purposes, but C does not provide such a type, so you have to implement it yourself.
Upvotes: 3
Reputation: 658
Enum in C are nothing more than a mapping between names and integers. So you could do something like
enum Fruit{apple, orange, banana};
array[apple][banana] = 1;
But like its name points, you must enumerate it, BEFORE you use it. So it's impossible to add one at runtime. Some kind of map structure might work though.
Upvotes: 2