int colors[][3] = {
{ 255, 0, 0 },
{ 0, 255, 0 },
{ 0, 0, 255 },
{ 253, 7, 210 }
};
int (*EXCLUSIVE_COLOR)[3];
I have a two-dimensional array to store some color values.
I have a 2nd array, which I am using to assign an "EXCLUSIVE_COLOR" from the first colors array.
What is the best method to assign a null or empty value to the "EXCLUSIVE_COLOR" array to be used upon initialization and when the "EXCLUSIVE_COLOR" is unset?
Initially I tried just assigning a default value to the array upon initialization:
int (*EXCLUSIVE_COLOR)[3] = {0,0,0};
//Produces an error: scalar object ‘EXCLUSIVE_COLOR’ requires one element in initializer
int (*EXCLUSIVE_COLOR)[3] = {0};
//assigns non-zero values to all three elements
I know that I can add a "dummy" record to the colors array to reference, when there isn't an "EXCLUSIVE_COLOR" set.
int colors[][3] = {
{ 255, 0, 0 },
{ 0, 255, 0 },
{ 0, 0, 255 },
{ 253, 7, 210 },
{ 0, 0, 0, } //dummy record
};
int (*EXCLUSIVE_COLOR)[3] = &colors[4];
However I wanted to know if there was a cleaner way to be able to assign an empty value to reference when a color is not set, and when the array is initialized.
1 Answer 1
If you're using a pointer then there's no limit to what that pointer can point to.
The way I see it you have two sensible choices:
- Point to a default value
This doesn't have to be in your array. It can be anything that is an int[3]
, since that is what your array consists of.
int[3] nothing = {0, 0, 0};
EXCLUSIVE_COLOR = nothing;
This means that it's actually pointing to something valid, in this case it's actually (I assume) the colour black. That can make it easy to deal with, since EXCLUSIVE_COLOR[0]
will be a valid value.
- Point to nothing
You can point your pointer to NULL
and it will be pointing to "nothing". This means that EXCLUSIVE_COLOR[0]
is no longer valid, which can make handling it somewhat harder. However it does allow you to distinguish between "nothing" and "black", unlike option 1.
For example:
EXCLUSIVE_COLOR = colors[2]; // {0, 0, 255}
...
EXCLUSIVE_COLOR = NULL; // Not pointing anywhere
To test if it's pointing somewhere you can simply use if
:
if (EXCLUSIVE_COLOR) {
// you have a valid entry
}
int* EXCLUSIVE_COLOR = {0,0,0};
read my comment or the edit at the end of Edgar's answer