如何静态初始化结构数组?

时间:2014-02-05 11:29:50

标签: c struct

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;

我想用{的副本初始化b。但是,我无法通过static const触及memcpy()件事。我需要bstatic const,因为这样它会被放入闪存而不是内存。

如何使这项工作。我认为编译器为arm-none-eabi-gcc -std=c89

3 个答案:

答案 0 :(得分:1)

我建议您将这些数组放在单独的模块中以实现封装。然后在该模块中,您不需要将B设为const而是将其设为静态。 任何对此数据的访问都必须通过这样的getter和setter来完成:


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);
}


答案 1 :(得分:1)

您可以试试这个,虽然它专门针对您指定的尺寸(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}};

答案 2 :(得分:0)

在linux上,这符合gcc -std = c89(不知道arm交叉编译器)

typedef struct A{
    int a; int b;
} TA;

typedef struct ARR3 {
    TA a[3];
} TARR3;


typedef struct ARR33 {
 TARR3 b[3];
} TARR33;

static const TA a = {.a = 1, .b = 42};

TARR33 aa = {
   .b[0] = { .a[0] = {.a = 1, .b = 1}, .a[1] = {.a = 2, .b = 2}, .a[2] = {.a = 3, .b = 3} },
   .b[1] = { .a[0] = {.a = 4, .b = 4}, .a[1] = {.a = 5, .b = 5}, .a[2] = {.a = 1, .b = 2} },
   .b[2] = { .a[0] = {.a = 1, .b = 1}, .a[1] = {.a = 1, .b = 2}, .a[2] = {.a = 1, .b = 2} }
            };

main()
{
  return 0;
}