Efficient storage of parameters in C [closed] - c

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have an application where I need to store values, those values can be either a double, an integer, a string (fixed size char array), uint8_t, chars, ...
Each of these values also has additional parameters, it can be Read-Only, Read-Write or they can have a max or min value (obviously for numeric types only).
So basically a simple struct would look like this:
typedef struct {
uint32_t current_val;
uint32_t min;
uint32_t max;
uint8_t type;
uint32_t initial_value;
uint8_t access_mode = READ_WRITE;
} valueType;
Now obviously this struct could only hold a uint32_t parameter value. I'd like to have many of those with different types and then store them in a common array.
Do you see any chance of doing this except for storing the reference to the instance and then finding out what the parameter type actually is?
I've seen a solution where for each of those parameters a memory section was allocated and then parameter was stored there. So basically the largest parameter was a 32byte string which caused even an uint32_t to occupy 32 bytes.
What would be the correct way to address this issue? Is there some common way to do this? Maybe just throw in some term so I know what to google for.

Efficient storage of parameters in C
Let us assume a fixed size per parameter.
So basically the largest parameter was a 32byte string
So we need at least 32 bytes. Use a union to overlay the various types of data.
typedef union {
char s[32];
TBD;
} valueType;
A string always ends with a null character so code can use the last char string[32-1] zero-ness as a flag for string vs. non-string.
For other types, keep track via a .type_identifier member.
typedef union {
char string[32];
struct {
union {
struct { uint32_t val; uint32_t min; uint32_t max; uint32_t initial; } t_uint32;
struct { float val; float min; float max; float initial; } t_float;
struct { char val; char min; char max; char initial; } t_char;
} u;
uint8_t type_identifier;
uint8_t access_mode;
} not_string;
} valueType;
This is fine when the size of .not_string is less than the size of .string.
Yet OP wants to code double, which commonly takes 8 bytes each and also wants 4 doublemembers.
So might as well:
typedef struct {
int type_identifier; // or uint8_t
int access_mode; // or uint8_t
union {
char string[32];
struct { uint32_t val; uint32_t min; uint32_t max; uint32_t initial; } t_uint32;
struct { double val; double min; double max; double initial; } t_double;
struct { float val; float min; float max; float initial; } t_float;
struct { char val; char min; char max; char initial; } t_char;
} u;
} valueType;
This may be as small as 2 + 32 bytes or a tad larger depending on padding requirements.

Unions are the way to go! Have an enum saying what type is stored there (I've used an int_8 to make the example small) and then do this:
struct {
int_8 type;
union {
int_8 eight_wide_thing;
char char_buffer[42];
double more_bad_variable_names;
}
int_32 foo_count;
} example;
You can do this:
struct example bar;
bar.eight_wide_thing = 42;
printf("%d", bar.eight_wide_thing);
bar.char_buffer[3] = '\0';
bar.char_buffer[0] = 'H';
bar.char_buffer[1] = 'i';
bar.char_buffer[2] = '!';
printf("%s", bar.char_buffer);
But not this:
bar.eight_wide_thing = 42;
bar.more_bad_variable_names /= 6;

Related

Is it possible to access the different Structure with same members by using Macros or any other functionality at runtime?(Structure updated))

In this code contains two structures and their naming is different. Structure member naming is same but type is different. Is there any possibility to change the structure name at run time by using macros or other functionality.
typedef struct STag_ABCRegisters
{
unsigned long aaa;
unsigned long bbb;
unsigned long ccc;
unsigned long dddd;
}RegistersABC;
typedef struct STag_CDERegisters
{
unsigned short aaa;
unsigned short bbb;
unsigned short ccc;
unsigned short dddd;
}RegistersCDE;
main()
{
int type = 1;
if(type == 1)
{
RegistersABC->ccc = 10;
}
else
{
RegistersCDE->ccc = 10;
}
/* after some process again checking the type updating structure*/
type = 2;
if(type == 1)
{
RegistersABC->aaa = 10;
}
else
{
RegistersCDE->aaa = 10;
}
}
I need the help for following process
In the above code contains complexity of if else condition.
So is there any possibilities for select the structure at run time??.
See the below Pseudo code steps for your understanding
main()
{
char type = "ABC";
Registers//type//->aaa = 10; // Type of structure name should be replaced here
}
As I stated in my comment, structures are just the way memory is organized on the machine.
If both structures were compiled by the same compiler on the same machine (architecture / OS), their memory footprint will be the same and you can simply cast their pointer to one to a pointer of the other.
This, however, is not the best way to go about "inheritance" with C.
At the moment, you can have something like this:
struct STag_ABCRegisters
{
unsigned short aaa;
unsigned long bbb;
unsigned short ccc;
unsigned short dddd;
} RegistersABC;
struct STag_CDERegisters
{
unsigned short aaa;
unsigned long bbb;
unsigned short ccc;
unsigned short dddd;
} RegistersCDE;
main()
{
(struct STag_CDERegisters*) pdata = (struct STag_CDERegisters*)&RegistersABC;
data->ccc = 10;
data->aaa = 10;
}
It works, but it isn't beautiful.
If you need two of the same, the correct way would be:
struct STag_Registers
{
unsigned short aaa;
unsigned long bbb;
unsigned short ccc;
unsigned short dddd;
};
struct STag_Registers RegistersABC, RegistersCDE;
main()
{
struct STag_Registers * data = &RegistersABC;
data->ccc = 10;
data->aaa = 10;
}
If you need struct inheritance, then the "trick" is to have the "parent" placed at the head of the struct, so that the memory footprint is aligned.
struct STag_Registers
{
unsigned short aaa;
unsigned long bbb;
unsigned short ccc;
unsigned short dddd;
};
struct STag_RegistersExtended
{
struct STag_Registers parent;
// ... more types
};
This allows a pointer to struct STag_RegistersExtended to be cast as a pointer to struct STag_Registers, so that functions that accept a pointer to struct STag_Registers can also accept a pointer to struct STag_RegistersExtended.
Good luck with C.
EDIT (answering comment)
If you're writing for an embedded system and you have reserved (fixed) memory addresses for the data, you could go with something such as:
typedef struct {
unsigned short aaa;
unsigned long bbb;
unsigned short ccc;
unsigned short dddd;
} register_s;
#define PTR2REG(p) ((register_s *)(p))
#define REG_A PTR2REG(0x1000))
#define REG_B PTR2REG(0x9000))
inline void perform_work(register_s * reg)
{
reg->ccc = 10;
// ...
reg->aaa = 10;
}
main()
{
perform_work(REG_A);
perform_work(REG_B);
if(REG_A->aaa == 10) // should be true
printf("work was performed");
}
You should note that struct have a memory alignment and packing order. The compiler will add padding to the struct you defined in the question, due to the long's memory alignment requirements. You can read more about struct packing here.
If your embedded system requires an exact bit / byte match (and is free from padding requirements), you should tell the complier not to add any padding. This is often done using #pragma pack
EDIT 2
I'm not sure where the type in your question is derived from... but if you have a global variable with the address for the struct, you could go with:
typedef struct {
unsigned short aaa;
unsigned long bbb;
unsigned short ccc;
unsigned short dddd;
} register_s;
#define PTR2REG(p) ((register_s *)(p))
#define REG_A PTR2REG(0x1000))
#define REG_B PTR2REG(0x9000))
register_s * active_register = REG_A;
inline void perform_work(void)
{
active_register->ccc = 10;
// ... active_register might change
active_register->aaa = 10;
}
main()
{
perform_work();
}
This is from a C++ perspective, you really should be more careful with those language tags if this is not what you want
Since C++ does not have reflection, it's not possible to do what you want at runtime. There are workarounds though.
For example one workaround could be to have a common base-class for the common elements (which in your simple example seems to be all). The you could have an unordered map translating strings to pointers to your structure.
Example:
struct CommonBase
{
unsigned short aaa;
unsigned long bbb;
unsigned short ccc;
unsigned short dddd;
};
struct ABC : CommonBase {};
struct DEF : CommonBase {};
int main()
{
std::unordered_map<std::string, std::unique_ptr<CommonBase>> items = {
{ "ABC", new ABC },
{ "DEF", new DEF }
};
std::cout << "Select item to modify (ABC or DEF): ";
std::string input;
std::cin >> input;
items[input]->aaa = 12;
}
For members that are not common, that are unique for each respective structure, then you need to actually check like you do now and then downcast the pointer to the correct type.
For a C solution there is none really, except to manually check like you do now.
Dynamic languages like python have buildin metadata table for reflection, so we just build one for help. Now it looks much like a script language.
_Generic need C11 std to work.
some code copied from How to save the result of typeof?
// some code copied from https://stackoverflow.com/questions/42222379/how-to-save-the-result-of-typeof
// gcc -std=c11 typeid_of_test.c
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
typedef struct STRU
{
int32_t aaa;
double bbb;
int ccc;
char dddd;
}STRU;
typedef struct Metainfo
{
int type;
char* name; //or hash
int offset;
}Metainfo;
enum {TYPE_UNKNOWN, TYPE_INT, TYPE_CHAR, TYPE_DOUBLE};
#define typeid_of(T) _Generic((T), int: TYPE_INT, long: TYPE_INT, char: TYPE_CHAR, double: TYPE_DOUBLE, default: 0)
#define META(ST_, M_) {typeid_of((__typeof__(((ST_ *)0)->M_))0), #ST_ "." #M_, offsetof(ST_, M_)}
/* { typeid, name, offset } */
Metainfo meta[]={
META(STRU, aaa),
META(STRU, bbb),
META(STRU, ccc),
META(STRU, dddd),
};
int set_by_name(char* member_name, char* value, void* p)
{
int offset=0, type=0;
for(int i=0; i<sizeof(meta)/sizeof(Metainfo); i++)
if(stricmp(member_name, meta[i].name)==0)
{
offset=meta[i].offset;
type = meta[i].type;
}
switch(type)
{
case TYPE_INT:
*(int*)((char*)p+offset) = atoi(value);
break;
case TYPE_CHAR:
*(char*)((char*)p+offset) = atoi(value);
break;
case TYPE_DOUBLE:
*(double*)((char*)p+offset) = atof(value);
break;
default:
return 0;
}
return 1;
}
int main(void)
{
for(int i=0; i<sizeof(meta)/sizeof(Metainfo); i++)
printf("type:%d, name: %s, offset: %d\n", meta[i].type, meta[i].name, meta[i].offset);
STRU b={0};
set_by_name("stru.bbb", "3.1415926", &b);
printf("stru.bbb == %f", b.bbb);
return 0;
}

Varying the Size of a Structure?

I have created a structure called Register, with around 8 fields within it. I now want to create a structure called Instrument, which should have a variable amount of of fields, 6 which are the same for every instrument, plus a certain amount of fields depending on how many registers are attributed to it. How can I create this?
For clarity here is what I would like to create (although may not be accurate).
typedef struct {
int x;
int y;
int z;
} Register;
typedef struct {
int x;
int y;
int z;
Register Reg1;
Register Reg2;
...
} Instrument;
You can make use of flexible array members to achieve the same.
Something like
typedef struct {
int x;
int y;
int z;
Register Reg1;
Register Reg2; //upto this is fixed....
Register Reg[];
} Instrument;
and then, you can allocate memory as needed to someVar.Reg later.
For an example, quoting C11, chapter ยง6.7.2.1/20
EXAMPLE 2 After the declaration:
struct s { int n; double d[]; };
the structure struct s has a flexible array member d. A typical way to use this is:
int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));
and assuming that the call to malloc succeeds, the object pointed to by p behaves, for most purposes, as if
p had been declared as:
struct { int n; double d[m]; } *p;
You can use pointers
typedef struct
{
int x;
int y;
int z;
Register *reg;
} Instrument;
use it into code
Instrument a.reg = malloc(sizeof(Register)*NUM_OF_REGISTERS);
if (a.reg != NULL)
{
// your STUFF
free(a.Reg);
}

Reading and writing bitmaps in c

I'm trying to create an application that inverts the colors of a bitmap file but am having some trouble with actually gathering the data and from the bitmap. I'm using structures to keep the data for the bitmap and it's header. Right now I have:
struct
{
uint16_t type;
uint32_t size;
uint32_t offset;
uint32_t header_size;
int32_t width;
int32_t height;
uint16_t planes;
uint16_t bits;
uint32_t compression;
uint32_t imagesize;
int32_t xresolution;
int32_t yresolution;
uint32_t ncolours;
uint32_t importantcolours;
} header_bmp
struct {
header_bmp header;
int data_size;
int width;
int height;
int bytes_per_pixel;
char *data;
} image_bmp;
Now for actually reading and writing the bitmap I have the following:
image_bmp* startImage(FILE* fp)
{
header_bmp* bmp_h = (struct header_bmp*)malloc(sizeof(struct header_bmp));
ReadHeader(fp, bmp_h, 54);
}
void ReadHeader(FILE* fp, char* header, int dataSize)
{
fread(header, dataSize, 1, fp);
}
From here how do I extract the header information into my header structure?
Also if anyone has any good resources over reading and writing bitmaps, please let me know. I have been searching for hours and can't find much useful information over the topic.
You actually should already have all the data in the correct places. The only issue possibly gone wrong could be endianness. e.g. is the number 256 represented in "short" as
0x01 0x00 or 0x00 0x01.
EDIT: there is something wrong related to the syntax of struct...
struct name_of_definition { int a; int b; short c; short d; };
struct name_of_def_2 { struct name_of_definition instance; int a; int b; }
*ptr_to_instance; // or one can directly allocate the instance it self by
// by omitting the * mark.
struct { int b; int c; } instance_of_anonymous_struct;
ptr_to_instance = malloc(sizeof(struct name_of_def_2));
also:
ReadHeader(fp, (char*)&ptr_to_instance->header, sizeof(struct definition));
// ^ don't forget to cast to the type accepted by ReadHeader
In this way you can directly read data into the middle of the struct, but the possible issue of endianness still lurks around.

How to break struct members into bytes of a single word

Say I have a C structure like:
typedef struct {
UINT8 nRow;
UINT8 nCol;
UINT16 nData; } tempStruct;
Is there a way to put all of those 3 members of the struct into a single 32-bit word, yet still be able to access them individually?
Something with the help of unions?
typedef struct {
UINT8 nRow;
UINT8 nCol;
UINT16 nData;
}
tempStruct;
typedef union {
tempStruct myStruct;
UINT32 myWord;
} stuff;
Or even better (with no "intermediate" struct):
#include <stdlib.h>
#include <stdio.h>
typedef union {
struct {
int nRow:8;
int nCol:8;
int nData:16;
};
int myWord;
} stuff;
int main(int args, char** argv){
stuff a;
a.myWord=0;
a.nCol=2;
printf("%d\n", a.myWord);
return 0;
}
What about just referring to it as a UINT32? It's not like C is type-safe.
tempStruct t;
t.nRow = 0x01;
t.nCol = 0x02;
t.nData = 0x04;
//put a reference to the struct as a pointer to a UINT32
UINT32* word = (UINT32 *) &t;
printf("%x", *word);
You can then get the value of the struct as a 32-bit word by dereferencing the pointer. The specifics of your system may matter, though...if I run this on my machine, the value of word is 0x00040201---that is, the fields are in reverse order. I don't think that's necessarily going to be the case if you're trying to serialize this to another system, so it's not portable.
If you want to actually store it as a 32-bit integer and then refer to the fields individually, why not
UINT32 word = 0x01020004;
and then somewhere else...
UINT8* row(UINT32 word) {
return (UINT8 *) &word + 3;
}
UINT8* col(UINT32 word) {
return ((UINT8 *) &word) + 2;
}
UINT16* data(UINT32 word) {
return ((UINT16 *) &word);
}
Macros will facilitate portable endianness.
Yes, you can use bit fields in C to do that. Something like:
typedef struct {
unsigned nRow : 8;
unsigned nCol : 8;
unsigned nData : 16;
} tempStruct;
If you want to control the memory layout also, you might want to take a look at #pragma pack. A non-portable option available on some compilers for this.
typedef struct {
int nRow:8;
int nCol:8;
int nData:16; } tempStruct;
nRow will take only 8 bit and nCol will take 8 bit and nDate will take 16bit.
This will work for you.
I just wrote sample program to see the size of it
#include<stdio.h>
typedef struct {
int nRow:8;
int nCol:8;
int nData:16; } tempStruct;
typedef struct {
int nRow;
int nCol;
int nData; } tempStructZ;
int main(void) {
printf("%d\n", sizeof(tempStruct));
printf("%d\n", sizeof(tempStructZ));
return 0;
}
Output:
4
16

Casting struct into int

Is there a clean way of casting a struct into an uint64_t or any other int, given that struct in <= to the sizeof int?
The only thing I can think of is only an 'ok' solution - to use unions. However I have never been fond of them.
Let me add a code snippet to clarify:
typedef struct {
uint8_t field: 5;
uint8_t field2: 4;
/* and so on... */
}some_struct_t;
some_struct_t some_struct;
//init struct here
uint32_t register;
Now how do i cast some_struct to capture its bits order in uint32_t register.
Hope that makes it a bit clearer.
I've just hit the same problem, and I solved it with a union like this:
typedef union {
struct {
uint8_t field: 5;
uint8_t field2: 4;
/* and so on... */
} fields;
uint32_t bits;
} some_struct_t;
/* cast from uint32_t x */
some_struct_t mystruct = { .bits = x };
/* cast to uint32_t */
uint32_t x = mystruct.bits;
HTH,
Alex
A non-portable solution:
struct smallst {
int a;
char b;
};
void make_uint64_t(struct smallst *ps, uint64_t *pi) {
memcpy(pi, ps, sizeof(struct smallst));
}
You may face problems if you, for example, pack the struct on a little-endian machine and unpack it on a big-endian machine.
you can use pointers and it will be easy
for example:
struct s {
int a:8;
int b:4;
int c:4;
int d:8;
int e:8; }* st;
st->b = 0x8;
st->c = 1;
int *struct_as_int = st;
hope it helps
You can cast object's pointer to desired type and then resolve it. I assume it can be a little bit slower than using unions or something else. But this does not require additional actions and can be used in place.
Short answer:
*(uint16_t *)&my_struct
Example:
#include <stdio.h>
#include <stdint.h>
typedef struct {
uint8_t field1;
uint8_t field2;
} MyStruct;
int main() {
MyStruct my_struct = {0xFA, 0x7D};
uint16_t num_my_struct = *(uint16_t *)&my_struct;
printf("%X \n", num_my_struct); // 7DFA
return 0;
}

Resources