1

I want to make 64 4-Byte long array and I want the start address to be what I want, say 0x1000_0000.

int wspace[64];  //this makes a 64 int array

I want wspace to be located at a particular location of my choice.
How Can I do that?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Rgarg
  • 496
  • 3
  • 6
  • 13
  • Please specify your environment and why you have a need to be in control of the address of your allocated RAM – Lee Taylor Dec 12 '14 at 02:29
  • The linker should have an input file that partitions memory and maps variables to specific partitions, or even addresses within a partition. That file is not standardized, so the answer to your question depends on which tool chain you're using, and which OS/processor you're targeting. – user3386109 Dec 12 '14 at 02:32

2 Answers2

4

You're starting to get into a grey area of possibly undefined behaviour but, if you know what you're doing (such as if you're on an embedded system and you have memory-mapped I/O or other valid writable stuff at that location), then you can just try:

int *wspace = (int *)0x10000000;

Depending on your compiler and environment, you may want to mark it as volatile as well, so that the implementation understands the memory may change independently of anything done to it by said compiler:

volatile int *wspace = (volatile int *)0x10000000;

It's not technically an array but, unless you're going to do something like sizeof on it, that probably won't really matter.

Once you've done that, then a statement like wspace[1] = 0x12345678 should write that value to memory locations 0x10000004-0x10000007 (for a 4-byte int). Just keep in mind that which part of the number goes into which memory location will depend on the endian-ness of your architecture.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • You also need `volatile`, if this is indeed a memory mapped IO region. This, along with some other useful techniques, is explained here: http://stackoverflow.com/questions/2389251/pointer-to-a-specific-fixed-address – void_ptr Dec 12 '14 at 05:20
  • Whether you _need_ volatile depends on a lot of things, including the standard you're working against, but you're right that it's a good idea. I'll update the answer. – paxdiablo Dec 12 '14 at 05:24
2

You can create a section in the linker file which start at this address and put this variable only in this section, the possibility of doing this will depend on your architecture.