I wanted to write a function that takes two arguments: a void pointer type to an arbitrary memory-block and a block bytesize. Knowing the struct type of data writen in the block, the function should print the values contained.
However, at first, the code I suggested didn’t work:
#define RECORD struct record
struct record {
char nam[32];
double val;
};
void xprint (void *p, long j)
{
j /= sizeof(RECORD);
RECORD r;
while(j--){
r = *((RECORD *)p++);
printf("\n..%s.., ..%lf..\n",r.nam, r.val);
}
return;
}
So, I came up with some alternations, mainly in the incrementing part of the code:
void print (void *p, long j)
{
j /= sizeof(RECORD);
RECORD r = *((RECORD *)p);
while(j--){
printf("\n%s,\t%8.2lf\n",r.nam, r.val);
r = *(++(RECORD *)p);
}
return;
}
Now it did the job, but still the code looks less compact.
After some inspection, I found the problem lies in r = *((RECORD *)p++); line. It seems that when it comes to a postfix incrementation, p is no longer typecasted, and hence p is incremented by one byte only.
Could the xprint function be rewritten so that I would still use the postfix operator, but applied to a typecasted pointer?
Convert the
void *to aRECORD *straight away and then use that pointer for the rest of the function.I also made some stylistic changes here, such as better variable names and adding
const.On a side note, as Clement Rey says it’d be better to use a typedef than a define.
You can even combine the typedef with the struct definition: