Assigning unknown values in an array to variables
Okay so I have an array of 9 integers. Some of values are given some and some are unknown. How would I assign a integer variable such as 'a' - 'z' to these unknown values? For example:
index [0] is unknown
index [1] is 27
index [2] is 6
index [3] is 9
index [4] is unknown
index [5] is 21
index [6] is 24
index [7] is 3
index [8] is unknown
I want
index [0] is a
index [开发者_高级运维1] is 27
index [2] is 6
index [3] is 9
index [4] is b
index [5] is 21
index [6] is 24
index [7] is 3
index [8] is c
for (ii=0; ii<MAXLINE/2; ii++)
{
if (uniqueNumbers[ii] == UNKNOWN_INPUT)
{
printf("UNKOWN_INPUT at [%d]\n", ii);
}
}
This is a great question. There actually is no straightforward way to do this in C, since the type system, while weak, does enforce that you pick a type for each variable, meaning that without some extra structure you won't be able to have the array elements be either an int or a reference to a variable.
One way to do this is to have your array elements each be a tagged union, such as this one:
typedef struct {
enum { Constant, Variable } type;
union {
int value; // If this is a constant
int* ref; // If this is a reference to a variable
} value;
} Expression;
Now, your array elements can be either a Constant (in which the value field is set) or a Variable, in which case the ref field would be a pointer to the actual variable holding the value.
If this isn't quite what you want, you can easily make modifications. If you want to store symbolic references instead of hard references (e.g. To store that an entry is "the variable X" instead of "a pointer to some other value"), you could add another enumerated constant and a field holding the name of the variable.
This is not possible with an array of type int
. You should probably define a small struct
with an int
and a char
and make an array of that.
struct values {
int value;
char variable;
};
Then you'd assign an arbitrary character (say ' '
) to variable
if you know the value of value
or a letter if you don't.
When using this, if variable
is set to ' '
(or whatever you defined) then go read the value of value
, otherwise handle as an unknown.
Expanding on @Argote's answer, the clean solution is to use an array of
struct Value {
union {
char var;
int i;
} v;
bool value_known;
};
The quick hack is to use the values -'a'
through -'z'
as variables. That only works if your values are always non-negative.
Since you do not seem to use negative values (you mark unknown with -1) you could just use the negative ASCII value of the chars to store this information.
index [0] is a (-97)
index [1] is 27
index [2] is 6
index [3] is 9
index [4] is b (-98)
index [5] is 21
index [6] is 24
index [7] is 3
index [8] is c (-99)
When printing use (char)(-1 * index[i])
.
If what you want is to print a letter for any value that is -1, then you need to put support for this code into your output routine.
精彩评论