I have a the following struct
typedef struct mainstruct {
uint32_t var1;
field_struct var2[2];
uint32_t var3;
} main_struct;
where field_struct is :
typedef struct fieldstruct {
uint8_t var11[8];
uint32_t var22;
uint32_t var33;
uint8_t var44[16];
uint8_t var55[16];
uint8_t var66[16];
} field_struct;
How can I initialize all the field_struct field in main_struct to all zeroes ?
Also var1 and var2 need to be initialized to specific values.
If you partially initialize the struct, the rest of the members that you don't initialize explicitly are set to zero. So it is enough to just initialize those members that need specific values:
main_struct ms =
{
.var1 = something,
.var2 = { something_else },
};
How can I initialize all the field_struct field in main_struct to all zeroes?
If you don't have access to designated initializers (C99 and C11), you can simply zero-initialize the entire struct and then initialize the rest to whatever you need:
main_struct s = {0};
s.var1 = ...;
The optimizer will do the right thing. Of course, if you don't want to initialize everything, you would have to manually initialize the ones you need only.
If you're trying to set default values for struct members then you simply can't do it: structures are data types, not instances of data types.
Instead, if you only want to initialize the members of an instance of your data type then you can use the method described in Lundin's answer.
Related
I getting an incompatible-pointer-types error when trying to Initialize a typedef struct with a pointer to a char buffer.
The struct looks like this:
typedef struct otCryptoKey
{
const uint8_t *mKey; ///< Pointer to the buffer containing key. NULL indicates to use `mKeyRef`.
uint16_t mKeyLength; ///< The key length in bytes (applicable when `mKey` is not NULL).
uint32_t mKeyRef; ///< The PSA key ref (requires `mKey` to be NULL).
} otCryptoKey;
This is what i have tried, and i also tried to initialize with all the parameters in the struct.
uint8_t mKey[16] = "1234567891012131";
uint8_t *mKeyPointer = mKey;
otCryptoKey *aKey = {mKeyPointer};
Can anyone figure out why i get this error?
You're creating a pointer to a otCryptoKey and attempting to initialize it with a pointer to uint8_t. Those types are not compatible.
What you want is to create an otCryptoKey object and initialize the mKey member with that pointer.
otCryptoKey aKey = {mKey, sizeof mKey, 0};
That syntax initializes a struct, not a pointer to a struct.
You should instead do: otCryptoKey aKey = {mKeyPointer};
Or better yet, use named fields and lose the intermediate variable: otCryptoKey aKey = { .mKey = mKey };
I have the following struct definition:
typedef struct mb32_packet_t {
union {
struct {
uint16_t preamble;
uint8_t system_id;
uint8_t message_id;
uint8_t reserved;
uint32_t paylen;
};
uint8_t header[9];
};
uint8_t *payload;
uint16_t checksum;
} __attribute__((packed)) mb32_packet_t;
Now I would like to have another union, so that I can get an uint8_t body[] pointer to the entire packet object. Something like this:
typedef struct mb32_packet_t {
union {
struct {
union {
struct {
uint16_t preamble;
uint8_t system_id;
uint8_t message_id;
uint8_t reserved;
uint32_t paylen;
};
uint8_t header[9];
};
uint8_t *payload;
uint16_t checksum;
};
uint8_t body[?];
};
} __attribute__((packed)) mb32_packet_t;
The problem is that the payload field size is dynamically determined at runtime. Is there another way to accomplish this other than making payload fixed sized?
I basically want to send objects of this type through a network socket, so I need a uint8_t pointer that points to an object of this type. At the time of sending the object, I know the size of the entire object in bytes.
Introduction
The question is unclear, so I will discuss three apparent possibilities.
Fixed-length header followed by variable-length payload
A typical way to define a packet for a networking or messaging service is to have a fixed-length header followed by a variable-length payload. In modern C, the variable-length payload may be defined using a flexible array member, which is an array with no dimension at the end of a structure:
typedef struct
{
uint16_t preamble;
uint8_t system_id;
uint8_t message_id;
uint8_t reserved;
uint32_t paylen;
uint8_t payload[];
} mb32_packet_t;
Memory for such a structure is allocated use the base size provided by sizeof plus additional memory for the payload:
mb32_packet_t *MyPacket = malloc(sizeof *MyPacket + PayloadLength);
When you pass such an object to a routine that requires a char * or uint8_t * or similar type for its argument, you can simply convert the pointer:
SendMyMessage(…, (uint8_t *) MyPacket,…);
That cast, (uint8_t *) MyPacket, provides the pointer to the first byte of the packet requested in the question. There is no need to wedge another member into the structure or layer on a union or other declaration.
Prior to the introduction of flexible array members in C 1999, people would use one of two workarounds to create structures with variable amounts of data. One, they might just define a member array with one element and adjust the space calculations accordingly:
typedef struct
{
…
unsigned char payload[1];
} mb32_packet_t;
mb32_packet_t *MyPacket = malloc(sizeof *MyPacket + PayloadLength - 1);
Technically, that violated the C standard, since the structure contained an array of only one element even though more space was allocated for it. However, compilers were not as aggressive in their analysis of program semantics and their optimization as they are now, so it generally worked. So you may still see old code using that method.
Two, GCC had its own pre-standard implementation of flexible array members, just using an array dimension of zero instead of omitting a dimension:
typedef struct
{
…
unsigned char payload[0];
} mb32_packet_t;
Again, you may see old code using that, but new code should use the standard flexible array member.
Fixed-length header with pointer to variable-length payload
The payload-after-header form shown above is the form of packet I would most expect in a messaging packet, because it matches what the hardware has to put “on the wire” when sending bytes across a network: It writes the header bytes followed by the data bytes. So it is convenient to have them arranged that way in memory.
However, your code shows another option: The data is not in the packet but is pointed to by a pointer in the packet, with uint8_t *payload;. I would suspect that is a mistake, that the network or messaging service really wants a flexible array member, but you show it followed by another member, uint16_t checksum. A flexible array member must be the last member in a structure, so the fact that there is another member after the payload suggests this definition with a pointer may be correct for the messaging service you are working with.
However, if that is the case, it is not possible to get a pointer to the complete packet object, because the object is in two pieces. One contains the header, and the other, at some unrelated location in memory, contains the data.
As above, you can produce a uint8_t * pointer to the start of the packet with (uint8_t) MyPacket. If the messaging system knows about the pointer in the structure, that should work. If you have mistaken what the packet structure must be, it will fail.
Fixed-length header followed by fixed-length payload space
Code elsewhere on Stack Overflow shows a struct mb32_packet_t with a fixed amount of space for a payload:
typedef struct mb32_packet_t {
uint8_t compid;
uint8_t servid;
uint8_t payload[248];
uint8_t checksum;
} __attribute__((packed)) mb32_packet_s;
In this form, the packet is always a fixed size, although the amount of space used for the payload could vary. Again, you would obtain a uint8_t * pointer to the packet by a cast. There is no need for a special member for that.
This is possible, but not with a struct or union, because all parts of a struct or union need to have a known size. You can still use a struct for the header.
Because the body starts at a known location, there's a trick you can use to access it as if it was part of the structure. You can declare it with no size at all (a "flexible array member") or as 0 bytes (a GCC extension that predates the standard). The compiler will not allocate any space for it, but it will still let you use the name to refer to the end of the struct. The trick is that you can malloc extra bytes after the end of the struct, and then use body to refer to them.
typedef struct mb32_packet_t {
union {
struct {
uint16_t preamble;
uint8_t system_id;
uint8_t message_id;
uint8_t reserved;
uint32_t paylen;
};
uint8_t header[9];
};
uint8_t body[]; // flexible array member
} __attribute__((packed)) mb32_packet_t;
// This is not valid. The body is 0 bytes long, so the write is out of bounds.
mb32_packet_t my_packet;
my_packet.body[0] = 1;
// This is valid though!
mb32_packet_t *my_packet2 = malloc(sizeof(*my_packet2) + 50);
my_packet2->body[49] = 1;
// Alternative way to calculate size
mb32_packet_t *my_packet3 = malloc(offsetof(mb32_packet_t, body[50]));
my_packet3->body[49] = 1;
The flexible array member must be last. To access the checksum, you will need to allocate an extra 2 bytes, and use pointer arithmetic. Fortunately, this is just for the checksum, and not the entire header.
mb32_packet_t *my_packet = malloc(sizeof(*my_packet) + body_size + 2);
uint16_t *pchecksum = (uint16_t*)&my_packet.body[body_size];
// or
uint16_t *pchecksum = (uint16_t*)(my_packet.body + body_size);
After you fill in the header, body and checksum, then because they are contiguous in memory, a pointer to the header is also a pointer to the entire packet object.
I usually do it this way:
typedef struct
{
size_t payload_size;
double x;
char y[45];
/* another members */
unsigned char payload[];
}my_packet_t;
or if your compiler does not support FAMs
typedef struct
{
size_t payload_size;
double x;
char y[45];
/* another members */
unsigned char payload[0];
}my_packet_t;
So it the payload can be at the end of the header structure
I am having trouble declaring an array of structs prior to populating them with data.
My struct looks like this:
typedef struct {
uint8_t * p_data; ///< Pointer to the buffer holding the data.
uint8_t length; ///< Number of bytes to transfer.
uint8_t operation; ///< Device address combined with transfer direction.
uint8_t flags; ///< Transfer flags (see #ref NRF_TWI_MNGR_NO_STOP).
} nrf_twi_mngr_transfer_t;
And in my code I am trying to declare the array like this:
struct nrf_twi_mngr_transfer_t start_read_transfer[10];
However I get a compile error:
array type has incomplete element type 'struct nrf_twi_mngr_transfer_t'
I have searched around as I thought should be a common thing, but I can't figure out what I am doing wrong. Maybe because one of the elements is a pointer? But that pointer should be a fixed size right?
Many thanks
It looks like some explanations are in order. This code
typedef struct {
//...
} nrf_twi_mngr_transfer_t;
Already defines a type which can be used directly. In contrast,
struct nrf_twi_mngr_transfer_struct {
//...
};
Would define a struct name, and to access it you'd need to indicate that you are referring to a struct.
As a result, given two definitions above, you should define your arrays differently:
nrf_twi_mngr_transfer_t arr[10]; // if using typedef
struct nrf_twi_mngr_transfer_struct arr2[10]; // if using struct with no typedef
And just in case you are wondering,
struct {
//...
} nrf_twi_mngr_transfer_obj;
Defines an object of anonymous struct type.
I am currently working on my own octree in C. The tree will contain a few billion objects, so memory efficiency is key. To achieve this I currently use one struct with a flag and a union, but I think it is not clean and it is wasting space for the inner node because I only need an 8-bit flag but memory is being reserved for the 64-bit index. My code currently is as follows:
typedef struct _OctreeNode
{
uint64_t location_code;
union
{
uint8_t child_exists;
uint64_t object_index;
} data;
uint8_t type;
} OctreeNode;
I would like to split this up into two different structs. One leaf node and one inner node. As follows:
typedef struct _OctreeInnerNode
{
uint64_t location_code;
uint8_t child_exists;
uint8_t type;
} OctreeInnerNode;
typedef struct _OctreeLeafNode
{
uint64_t location_code;
uint64_t object_index;
uint8_t type;
} OctreeLeafNode;
Now the problem arises with my unordered map based on the hash of the location code. It uses a void pointer, so storing two different structs is not a problem. I know a possibility would be to have the flag be the first element and dereference the pointer to the flag datatype to derive the type, like so:
typedef struct _OctreeLeafNode
{
uint8_t type;
uint64_t location_code;
uint64_t object_index;
} OctreeLeafNode;
void
func(void* node)
{
uint8_t type = *(uint8_t*)node;
if (type == LEAF_NODE) {
OctreeLeafNode* leaf_node = (OctreeLeafNode*)node;
}
}
I was wondering if there is a cleaner way. Or is this not recommended? How would I be supposed to deal with multiple possibilities for structs and void pointers?
Thanks in advance!
This a method that is used commonly in C.
But just put these field at start of structure (first field) and never change their position. In addition, you need to keep them in all your structures.
A common sample for this approach is the version field in structures (or type in your case). You can keep them at start of structure, and then check structure version by similar method. something like this:
struct _base {
uint8_t ver;
};
#define TYPE_OLD 0
struct _a_old {
struct _base info;
uint8_t a;
};
#define TYPE_NEW 1
struct _a_new {
struct _base info;
uint8_t a;
uint8_t b;
};
Now you can identify different types by casting your data to struct _base and checking ver field.
unsigned char* buf = ...
switch (((struct _base*)buf)->ver)
{
case TYPE_OLD:
{
struct _a_old* old = (struct _a_old*)buf;
// ...
break;
}
case TYPE_NEW:
{
struct _a_new* old = (struct _a_new*)buf;
// ...
break;
}
default:
// ...
}
This will work, assuming the type field is first in each struct. A pointer to a struct may safely be converted to a pointer to its first member, so assuming your structs look like this:
typedef struct _OctreeInnerNode
{
uint8_t type; // type goes first
uint8_t child_exists; // put uint8_t members together to keep size down
uint64_t location_code;
} OctreeInnerNode;
typedef struct _OctreeLeafNode
{
uint8_t type; // type goes first
uint64_t object_index;
uint64_t location_code;
} OctreeLeafNode;
You can cast either a OctreeInnerNode * or a OctreeLeafNode * to a uint8_t *. Then this is possible:
void func(void* node) {
uint8_t type = *(uint8_t*)node;
if (type == LEAF_NODE) {
OctreeLeafNode *leafNode = node;
...
} else if (type == INNER_NODE) {
OctreeInnerNode *innerNode = node;
...
}
}
...
OctreeLeafNode leaf = { LEAF_NODE, 2, 3 };
OctreeInnerNode inner = { INNER_NODE, 5, 1 };
func(&leaf);
func(&inner);
This is guaranteed as per section 6.7.2.1p15 of the C standard:
Within a structure object, the non-bit-field members and the
units in which bit-fields reside have addresses that increase in
the order in which they are declared. A pointer to a structure
object, suitably converted, points to its initial member (or
if that member is a bit-field, then to the unit in which it
resides), and vice versa. There may be unnamed padding within
a structure object, but not at its beginning
How to initialise the table DetectionSensors in this structure:
typedef struct
{
DetectionSensor *DetectionSensors[];
unsigned char nbSensors;
} SENSOR_STRUCT;
SENSOR_STRUCT my_var = { } ?
This table contains just some DetectionSensor pointers;
You can't; the structure definition shown shouldn't compile.
typedef struct
{
DetectionSensor *DetectionSensors[]; // Not C
unsigned char nbSensors;
} SENSOR_STRUCT;
If you're trying for a flexible array member (FAM), that has to be the last field in the structure and you can't write initializers for structure containing a FAM.
Otherwise, you need to use an explicit size for the dimension of the array, or lose the array notation and use DetectionSensor *DetectionsSensors; (or conceivably, but it seems implausible) DetectionSensor **DetectionSensors;.
typedef struct
{
DetectionSensor *DetectionSensors[10]; // Use an enum or #define
unsigned char nbSensors;
} SENSOR_STRUCT;
With this, you need some DetectionSensors around:
DetectionSensor ds[10];
SENSOR_STRUCT my_var = { { &ds[0], &ds[1], &ds[2], &ds[3] }, 4 };
In general, reserve ALL_CAPS for macros (FILE and DIR notwithstanding).
If your intention is to initialise the structure with a predefined set of Detectionsensor, you can do like this.
DetectionSensor sample [] = {sensor1, sensor2];
my_var.DetectionSensors = sample;
There's no automatic constructor for C structs, first you need to build the DetectionSensors array and then assign the value of that array to the DetectionSensor variable in your SENSOR_STRUCT.
typedef struct
{
DetectionSensor * DetectionSensors;
unsigned char nbSensors;
} SENSOR_STRUCT;
DetectionSensor * sensors = ...; //get your detection sensors.
SENSOR_STRUCT my_var = {sensors, ... };
You should reserve some memory for the DetectionSensors, e.g. this way:
#define MAX_SENSORS 10
typedef struct
{
DetectionSensor *DetectionSensors[MAX_SENSORES];
unsigned char nbSensors;
} Sensor_Struct;
Sensor_Struct my_var;
myvar.DetectionSensors[0] = somePointer;
my_var.nbSensors = 1;
btw: CAPS_LOCKED_NAMES are by convention for preprocessor variables (#define SOMETHING abc)
You could provide functions to add a new sensor and even make the memory use dynamic, if you need that.