PIC XC8 compiler array of structs

mplabmplabxpicxc8

I'm having trouble assigning variables to structs, particularly making an array of structs, with the XC8 compiler.

Example code below:

typedef struct p{
  int id;
  dateStamp start;
  dateStamp stop;
  int parent_id;
} period;

period p1 = {1, {0, 0, 0, 1, 1, 14}, {20, 0, 0, 1, 1, 14}, 1};
period p2 = {1, {21, 0, 0, 1, 1, 14}, {50, 0, 0, 1, 1, 14}, 1};
period p3 = {1, {51, 0, 0, 1, 1, 14}, {59, 0, 0, 1, 1, 14}, 1};

period periods[3] = {p1, p2, p3};

And this is the compiler error log:

main.c:233: error: (188) constant expression required
main.c:233: error: (207) simple type required for "@"
main.c:233: error: (182) illegal conversion between types
struct p -> int
main.c:233: error: (181) non-scalar types can't be converted to other types
main.c:233: error: (188) constant expression required
main.c:233: error: (207) simple type required for "@"
main.c:233: error: (182) illegal conversion between types
struct p -> int
main.c:233: error: (181) non-scalar types can't be converted to other types
main.c:233: error: (188) constant expression required
main.c:233: error: (207) simple type required for "@"
main.c:233: error: (182) illegal conversion between types
struct p -> int
main.c:233: error: (181) non-scalar types can't be converted to other types
main.c:256: warning: (345) unreachable code
(908) exit status = 1
make[2]: *** [build/default/production/main.p1] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2

Suggestions would be welcome….

Best Answer

This is a C problem.

period periods[3] = {p1, p2, p3};

is invalid in C, as p1, p2 & p3 are struct variables, and not constants known at compile-time, therefore you cannot use them as initializers.

You may use macros to substitute the same constant values into p1, p2, p3 and periods[3] so that you don't have to duplicate the values:

#define P1 {1, {0, 0, 0, 1, 1, 14}, {20, 0, 0, 1, 1, 14}, 1}
#define P2 {1, {21, 0, 0, 1, 1, 14}, {50, 0, 0, 1, 1, 14}, 1}
#define P3 {1, {51, 0, 0, 1, 1, 14}, {59, 0, 0, 1, 1, 14}, 1}

period p1 = P1;
period p2 = P2;
period p3 = P3;

period periods[3] = { P1, P2, P3 };

Or you may simply avoid initializers altogether, and use explicit statements at the beginning of your program to initialize these arrays.