struct A{
int a; int b;
};
static const struct A a = {.a1 = 1, .a2 = 42};
struct B{
struct A[666][510]
};
static const struct B b;
I would like to initialize b
with copies of a. However, I cannot touch static const
things with memcpy()
. And I need b
to be static const
, because that way it gets put into flash and not ram memory.
How do I make this work. The compiler is arm-none-eabi-gcc
with -std=c89
, I think.
It is initialized only once, the first time the control passes through its declaration. 3. If a static array is not explicitly initialized, its elements are initialized with the default value which is zero for arithmetic types (int, float, char) and NULL for pointers.
Here is how initialize the structure : struct str { char arr1[4]; // this string is limited to three characters plus null char arr2[4]; int num1[4]; int num2[4]; }; struct str select = { "Sam", "Joe", { 0, 1, 2, 3 }, { 4, 5, 6, 7 } };
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
You can try this, though it works specifically for the dimensions that you specify (666 x 510):
#define X001 {1,42}
#define X002 X001,X001
#define X004 X002,X002
#define X008 X004,X004
#define X016 X008,X008
#define X032 X016,X016
#define X064 X032,X032
#define X128 X064,X064
#define X256 X128,X128
#define Y001 {X256,X128,X064,X032,X016,X008,X004,X002}
#define Y002 Y001,Y001
#define Y004 Y002,Y002
#define Y008 Y004,Y004
#define Y016 Y008,Y008
#define Y032 Y016,Y016
#define Y064 Y032,Y032
#define Y128 Y064,Y064
#define Y256 Y128,Y128
#define Y512 Y256,Y256
static const struct A a = X001;
static const struct B b = {{Y512,Y128,Y016,Y008,Y002}};
I recommend that you put these arrays in a separate module in order to achieve encapsulation. Then inside that module you do not need to make B a const but make it static instead. Any access to this data must be done via getters and setters like this:
mydata.h
#define BA_SIZE 666
struct A{
int a; int b;
};
struct B{
struct A stuff[BA_SIZE];
};
void init(void);
struct A * getB(unsigned int i);
void setB(unsigned int i, struct A element);
mydata.c:
#include "mydata.h"
static const struct A a = {.a = 1, .b = 42};
static struct B b;
void init(void)
{
int i;
for(i=0; i<BA_SIZE; i++) {
b.stuff[i] = a;
}
}
struct A * getB(unsigned int i)
{
return(&b.stuff[i]);
}
void setB(unsigned int i, struct A element)
{
if (i > BA_SIZE) { return; }
b.stuff[i].a = element.a;
b.stuff[i].b = element.b;
}
main.c:
#include <stdio.h>
#include "mydata.h"
int main(void)
{
init();
unsigned int num=1;
struct A * something = getB(num);
printf("element [%u] a=%i b=%i \n", num, something->a, something->b);
return(0);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With