In a very known C code distribuited under GPL3 I found the following program (I just report here a minimal example and not the whole code for simplifying).
#include <stdio.h>
typedef struct {
float *x;
} mystruct;
mystruct var_struct;
#define ALPHA 0
#define BETA 1
#define GAMMA 2
#define DELTA 3
#define MACRO1 var_struct.x[ALPHA]
#define MACRO2 var_struct.x[BETA]
#define MACRO3 var_struct.x[GAMMA]
#define MACRO4 var_struct.x[DELTA]
int main()
{
mystruct var_struct;
float a = 5.6f;
MACRO1 = a;
return 0;
}
I admit that I'm quite confused about this style of writing and using pointers, since I had preferred each separated fields for pointers in the structure itself and not a shared pointer. But this is what I found and - since I don't think that it could work - I decided to analyse the code step by step, so I can learn something new or understand something that I don't know yet.
Anyway if I run the code on the platform architecture (ARM7) it compiles and runs. If I try the same code on the gcc (GCC) 5.3.1 20151207 (Red Hat 5.3.1-2) it compiles but it doesn't run (Segmentation fault).
Question #1: To me wanted the programmer to use one shared pointer to a variable, which is going to be overwritten simply using the MACROx defined macros. But in this case I never can be sure which value as been assigned to the pointer *x, if I didn't track which macro I have already used. Or am I wrong?
Question #2: As stated here the #define macro simply replace text in the code. So even if I used MACRO1, MACRO2 or MACRO3... they simply refer to the same variable. In this case through its address in the memory. Or not?
Question #3: Is such a codestyle compatible with the most used and spreaded C techniques and C coding rules? I don't think so...but I m unsure. Maybe the programmer is using some very efficient methods for code writing, which are not very common.
UPDATE
Thanks to the many answers and comments.
Why I didn't post the code?!? Because otherwise I would reminded to post just a minimal example and not the whole code. So, it is just to respect rules. I don't hide anything.
So here the code. The structure I'm talking about is in nav_ukf.h
declared and it is called navUkfStruct_t
In the file nav_ukf.c
you can read in the function navUkfInitState()
how those defines are used.
I couldn't find any malloc
or calloc
.
Question #4: Since pointers must be allocated using one of the functions above (malloc, calloc), why the minimal example works?!?