9

I read this piece of macro(C code) and was confused in decoding it to know what it defines. What does it define?

#define sram (*((unsigned char (*)[1]) 0))

-AD

goldenmean
  • 18,376
  • 54
  • 154
  • 211

3 Answers3

12

I think sram means "start of RAM".


unsigned char[1]

An array of size 1 of unsigned chars.

unsigned char(*)[1]

A pointer to an array of size 1 of unsigned chars.

(unsigned char (*)[1]) 0

Cast 0 to a pointer to an array of size 1 of unsigned chars.

*((unsigned char (*)[1]) 0)

Read some memory at location 0, and interpret the result as an array of size 1 of unsigned chars.

(*((unsigned char (*)[1]) 0))

Just to avoid 1+5*8+1==42.

#define sram (*((unsigned char (*)[1]) 0))

Define the variable sram to the memory starting at location 0, and interpret the result as an array of size 1 of unsigned chars.

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • +1 for providing me with an explanation to that conundrum in the Hitchhiker's Guide five-part trilogy. Oh, and I guess the rest of your answer was okay too. – Platinum Azure Feb 23 '10 at 18:24
  • Or on an embedded system it could just mean "SRAM" (Static Random Access Memory) which is typically what a microcontroller's on-chip RAM is made of. – Clifford Feb 23 '10 at 18:40
1

I think it's returning the base address (0) of memory (RAM) :)

John Weldon
  • 39,849
  • 11
  • 94
  • 127
1

It defines "sram" as a pointer to memory starting at zero. You can access memory via the pointer, e.g. sram[0] is address zero, sram[1] is the stuff at address one, etc.

Specifically it is casting 0 to be a pointer to an array of unsigned char and going indirect through that (leaving an array of unsigned char).

A similar result can be obtained by

#define sram ((unsigned char*)0)

It is also completely undefined in standard C, but that doesn't stop people from using it and having angels fly out of their navels.

Richard Pennington
  • 19,673
  • 4
  • 43
  • 72