Question:
Initializing chosen array entries in C/C++?
fang_sharp
2008-11-03 08:26:58 UTC
I've came upon an interesting piece of syntax:

#define _RTCAN_WRITE_MSG 0
#define _RTCAN_READ_MSG 1
#define _RTCAN_GETUNIXTIME 2
#define _RTCAN_HOWMANY 3

static struct rt_fun_entry rtai_rtcandrv_fun[] = {
[_RTCAN_WRITE_MSG] = {0, rt_rtcanwrite},
[_RTCAN_READ_MSG] = {0, rt_rtcanread},
[_RTCAN_GETUNIXTIME] = {0, rt_getunixtime},
[_RTCAN_HOWMANY] = {0, rt_rtcanhowmany}
};

This one works, initializing an array of structures, with specifying which entry goes at which position.

I tried a similar code:

#define SOERR_BRAK_PWE 0
#define SOERR_BRAK_PZM 1
#define SOERR_BRAK_FWE 2
#define SOERR_BRAK_FZP 3
#define SOERR_NIESYM_TMZ 4
...

static unsigned char shobj_error_levels[] = {
[SOERR_BRAK_PWE] = 1,
[SOERR_BRAK_PZM] = 2,
[SOERR_BRAK_FWE] = 2,
[SOERR_BRAK_FZP] = 1,
[SOERR_NIESYM_TMZ] = 3,
...
};


The list is some 50 entries long, and I really don't like the idea of filling it as static unsigned char shobj_error_levels[] = { 1,1,2,2,1,3...} because of the likehood of making a mistake.
The second code doesn't work, saying " parse error before `=' token" at line which is the first line of data.

How do I use this syntax?
Three answers:
Germann A
2008-11-03 08:43:22 UTC
maybe you meant static unsigned short (or int)?
tanna
2016-05-25 20:08:56 UTC
This is an array size question, right? Array sizes can be manipulated, but they are done so by assigning the array a new array of the required size. This means you need a temporary variable to catch the old contents and copy them before deleting the old memory block.
Chris C
2008-11-03 08:46:42 UTC
I don't believe either of those should work.

As a matter of fact, once I found the structure that you were referencing, I attempted to compile that first bit of code that you posted, and it wouldn't compile.



Here's the structure that I used because it was defined in a different header file.

struct rt_fun_entry {

unsigned long long type;

void *func;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...