How can I specify an array at runtime?
What I'm Trying To Do
Basically, I've got several possible arrays that I define with macros:
#define ARRAY_ONE {0, 2, 7, 8}
#define ARRAY_TWO {3, 6, 9, 2}
#define ARRAY_THREE {3, 6, 4, 5}
//etc...
At runtime, I have a C-Array that gets used in a lot of places in a certain class. I want this array to use one of the #define values, i.e:
int components[4];
if (caseOne)
{
components = ARRAY_ONE;
}
else if (caseT开发者_运维问答wo)
{
components = ARRAY_TWO;
}
else if (caseThree)
{
//etc...
}
-
The Problem
However, the above code does not work. Instead, I get a weird error
Expected expression before '[' token
Would anyone mind explaining what's going on, and how I could achieve what I'm attempting to? Any help would be much appreciated - Thanks!
I don't think that C arrays can be initialized using the curly-brace syntax after they've been declared. You can only do that when initializing them while declaring them.
Try adjusting the previously posted answer with:
const int ARRAY_ONE[] = {0, 2, 7, 8};
const int ARRAY_TWO[] = {3, 6, 9, 2};
const int ARRAY_THREE[] = {3, 6, 4, 5};
int *components;
if (case1) {
components = ARRAY_ONE;
} else if (case2) {
components = ARRAY_TWO;
} else if (case3) {
components = ARRAY_THREE;
}
I can't really work out what the error is. I suspect it might be coming from some code you haven't posted. Does it say the error is on the int components[4];
line?
Would this do? I uses constants instead of defines.
const int ARRAY_ONE[] = {0, 2, 7, 8};
const int ARRAY_TWO[] = {3, 6, 9, 2};
const int ARRAY_THREE[] = {3, 6, 4, 5};
int* components = ARRAY_ONE;
int whatever = components[2];
try this:
int ARRAY_ONE[] = {0,2,7,8};
int ARRAY_TWO [] = {3,6,9,2};
int ARRAY_THREE[] = {3,6,4,5};
int components[4];
int count =sizeof(components)/4 //this will get array length, or you can just put array lenght ;
if (case1)
for (int i =0; i< count; i++) components[i] = ARRAY_ONE[i];
else if (case2)
for (int i =0; i< count; i++) components[i] = ARRAY_TWO[i];
精彩评论