Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Struct pointers and their initialization

I have a struct in C as follows:

typedef struct ENETPACKET_S {
    unsigned    n_rxcmd, n_txcmd;
    uint64_t    n_mac;  // 8 bytes unsigned or 64 bit
    unsigned    n_rxmiss, n_rxerr, n_rxcrc, n_txcol;
} ENETPACKET;

A pointer is being defined from the variable of this struct here below:

 static volatile ENETPACKET *const _net1 = ((ENETPACKET *)0x00500000);

I have two queries:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. I understand pointers to a struct, but in the declaration of _net1, a pointer from a variable/object of a struct is being defined. I don’t get that.

  2. I am confused by the ((ENETPACKET *)0x00500000) initialization of the const pointer, I don’t understand what is being initialized here and the brackets and the * operator.

>Solution :

It seems that you are working on an embedded device with possibly a micro-controller. In such systems, some peripherals can be configured/used by setting some registers. These registers can be read/written directly as it was memory available by your C program.

To give a small example of what it could looks like:

/* Control the PIN10 (input/output) */
/* The CONTROLLER of PIN10 is mapped at the address 0x00400000 */
static volatile uint8_t * const PIN10_CTRL = 0x00400000;

/* PIN10 control the output PIN of the MCU who is connected to a LED */
/* The STATUS of the PIN10 is mapped at the address 0x00400001 */
static volatile uint8_t * const PIN10 = 0x00400001;

*PIN10_CTRL = 0x1; /* Configure the PIN10 as a output PIN */

/* Blink the LED every second */
while (1)
{
  *PIN10 = 1;
   sleep(1);
  *PIN10 = 0;
   sleep(1);
}

If we consider your code now:

static volatile ENETPACKET *const _net1 = ((ENETPACKET *)0x00500000);

It seems like the networking interface of your micro-controller is putting the results of a ENETPACKET at the address 0x00500000. This address is fixed and can probably be found in the user manual of your micro-controller.

The structure is volatile to prevent the compiler to do any assumption on the binary code he will generate. If the keyword volatile was omitted, you could have some optimizations applied on the program and the data to be out-of-date.

This address 0x00500000 is probably the address of an array of N x ENETPACKET packets.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading