I want to set the base address of a matrix of float at a precise place in my memory (embedded DSP development)
I'd like to do something like this, which is not working :
// volatile because of the DMA filling the array automatically
// base address is 0x80000000
volatile float example_two[100][2] = (volatile float *)0x80000000;
I know I can do it for a pointer like this, but I'll loose the array size ([100][2]):
// volatile because of the DMA filling the array automatically
// base address is 0x80000000
volatile float *example_one = (volatile float *)0x80000000;
Is it possible ?
If you want to allocate memory at a fixed address, you must use non-standard ways and also modify the linker script. This is compiler/linker specific.
If the memory is already allocated at that position and you know for a fact that it is of type float [100][2]
, or of no type at all (untouched by compiler), then you can do use an array pointer:
volatile float (*example_two)[100][2];
example_two = (volatile float(*)[100][2]) 0x80000000UL;
In case of gcc, always disable strict aliasing in embedded sytems, just to be sure the compiler won't go haywire when for example reading a DMA buffer. gcc -fno-strict-aliasing
.
Consider:
volatile float (*example_two)[2] = (volatile float (*)[2]) 0x80000000;
This declaration allows you to use example_two
as if it had been declared with float example_two[100][2]
. For example, example_two[i][j]
refers to element j
of row i
. By creating a pointer to arrays of two elements, this omits the [100]
information from the type, but that is generally not needed.
Another option is to write:
volatile float (*example_two)[100][2] = (volatile float (*)[100][2]) 0x80000000;
This includes the full type information, but then it must be dereferenced to be used, as in (*example_two)[i][j]
. This is more cumbersome.
If you take these statements as in c language,
volatile float *example_one = (volatile float *)0x80000000;
here you make a pointer point to a location that you specify.
where as the following statement,
volatile float example_two[100][2]
creates an array. there is a memory allocation happening. So they are different statements.
You can create a pointer to an array in this case and try as,
volatile float (*example_two)[100][2] = (volatile float *)0x80000000;
You need to access the data then as (*example_two)[i][j]
Try (or don't try) this ugly #define
trick
#define example_two (*donttrythisathome)
float example_two[100][2] = (void*)0xDEADBEEF;
example_two[42][0] = example_two[42][1] = -0.42;
See working example on https://ideone.com/7c6dJ9
User contributions licensed under CC BY-SA 3.0