View previous topic :: View next topic |
Author |
Message |
SamMeredith
Joined: 13 Jul 2018 Posts: 23
|
Reference to structure in array |
Posted: Wed Apr 24, 2019 3:17 am |
|
|
Could anyone explain the following compiler error to me?
I am using compiler version 5.083
Code: |
#define num_foobars 10
typedef struct {
int property;
} foobar_t;
void init(foobar_t *foobars)
{
int i;
for (i = 0; i < num_foobars; i++)
{
foobars[i].property = 0;
}
}
void main()
{
foobar_t foobars[num_foobars];
init(foobars);
int m_property = foobars[0].property;
foobar_t *p_foobar = &foobars[0];
int m_pointer_property = p_foobar->property;
foobar_t m_foobar = foobars[0];
}
|
The error is on the last line of main() with the message
Quote: | ***Error 27 [..]: Expression must evaluate to a constant |
Why is it that I can reference elements of structs and create pointers to structs within an array, but not store references to the structure directly?
I would be interested in any mention of this in the manual (I couldn't spot anything in the Structures and Unions section) as well as the reason behind this behaviour. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19589
|
|
Posted: Wed Apr 24, 2019 4:11 am |
|
|
Generally, 'C' historically did not support inline type declarations.
In traditional C, you must declare all variables at the start of a code
section, and then use them later.
Now ANSI added the ability to do inline declarations, but there are
restrictions on the initialisations that can be done 'inline'.
So:
foobar_t m_foobar = foobars[0];
Can't be done. It requires the creation of a type, and then the copying
of variable data into this (which can't be done at compile time).
However
foobar_t m_foobar;
m_foobar = foobars[0];
Will work.
It allows the int declaration which has the similar issue, since it only
involves a one byte copy from a fixed location. Copying the entire
structure is more complex.
Generally it is much safer to stick with the traditional C style and
declare variables at the start of code sections, and only ever initialise
at declaration with constant values. You'll find it less likely to give issues.... |
|
|
SamMeredith
Joined: 13 Jul 2018 Posts: 23
|
|
Posted: Wed Apr 24, 2019 4:47 am |
|
|
Thanks Ttelmah.
I guess I've gotten in the habit of making inline declarations, I'll be more careful about that. |
|
|
|