Search code examples
cpointersavr

void pointer - Load structure from flash


I have some example code with a structure stored in the flash memory of an AVR microcontroller.

const MyStruct PROGMEM Struct =
{
   .MemberA = 1,
   .MemberB = 2,
}

The address of this structure is loaded with this function:

const void* StructAddr;
Load(&StructAddr);

void Load(const void** Address)
{
   const void* Temp = NULL;
   Temp = &Struct;
   *Address = Temp;
}

What is the reason for a void pointer in this case? If I try this way

const intptr_t StructAddr;
Load(&StructAddr);
void Load(const intptr_t Address)
{
   const void* Temp = NULL;
   Address = &Struct;
}

the content of StructAddr is 0x00. Why? What is the difference between this two solutions?


Solution

  • I'm not familiar with flash memory in a AVR controller, but in C we usually use void* to indicate a piece of memory which we don't know which type it holds(in contrast with, for example, intprt_t* representing the address of a piece of memory where its content should be interpreted as a int).

    In the first function it is passed a void**: you pass the address where a variable of type void* is located then by doing *Address = Temp; you fill the area in memory pointed by Address (thus out of the function the variable is updated).

    In the second function you have passed a intptr_t: here the same trick doesn't work since youassign to a local copy of the memory address StructAddr a new value, which is then discarded after the function terminated.

    As other in the comments said, you need intptr_t* in the signature of the second function and you need to perform the followin *Address = Temp.