So in my source file I have the folowin function:
void update(state* old_state, state* measurement, uint32_t size)
{
state new_state[size];
//some function using measurement and old_state and returning the result in newstate
arm_fadd_32(measurement,old_state,newstate,size);
// rest of the code
}
Now the compiler throws an error saying that
error#28:expression must have a constant value.
I think it’s due to the fact that even though inside the method the size local variable is not changing the compiler is expecting a constant while defining the size.
I have tried the following:
int const a = size;
and then tried to reinitialize it says constant value is not known.
I did some research in internet and it appears that there is no easier way without using malloc, which I don’t want to since I am using the code for some embedded application.
Is there a way to avoid this problem without really using malloc? Thanks in advance guys!
As of the 1990 ISO C standard, the size of an array must be a constant integer expression. Note “constant”, not
const. A constant expression is (roughly) one whose value is known at compile time;const, though it comes from the same root word, really just means “read-only”.The 1999 standard added VLAs (variable length arrays), which would make your code legal. One drawback of VLAs is that there’s no mechanism to detect a failure to allocate the required space; if the allocation fails, your programs behavior is undefined. (It may crash if you’re lucky.)
Most C compilers these days do support most of the C99 standard; you may need a command-line option to enable it. Microsoft’s C compiler, on the other hand, supports only C90, plus a very few C99-specific features, and Microsoft has stated that they have no plans to change that. If you’ll lets us know what compiler you’re using, we can probably be more helpful.
You can use
malloc()to allocate a dynamically sized array on the heap:Note that
malloc()returns a null pointer to indicate an allocation failure, which is an advantage over VLAs even if your compiler supports them.