Using Variables in Program Memory

Variables in program memory can be used almost exactly like variables in data memory. The exceptions are presented below:

Explicit conversions are allowed, but they should be used with care. An explicit conversion for the previous assignment that is accepted by the compiler is given below:

pxp1 = ( __pmem int * )ppx1;

Another consequence of this restriction is that an important part of the MSL functions that have at least an argument that is a pointer will not work with variables in program memory. For example:

char *c1; // pointer in data memory to char in data memory
char __pmem *c2; // pointer in data memory to char in program
memoryvstrcat( c1, c2 ); // error, the second argument can't be converted to 'const char *'

If variable argument lists are used, this problem is generally hidden. The program is compiled with no errors from the compiler, but it doesn't work as expected. The most common example is the printf function:

char *c1 = "xmem"; // pointer in data memory to char in data memory
char __pmem *c2 = "pmem"; // pointer in data memory to char in program memory
printf( "%s\n", c1 );     // works as expected
printf( "%s\n", c2 );     // doesn't work as expected

Here, the type of the arguments is lost because printf uses a variable argument list. Thus the compiler can not signal a type mismatch and the program will compile without errors, but it won't work as expected, because printf assumes that all the data is stored in data memory.