pointer jumping

Posted By: HeelX

pointer jumping - 05/09/13 19:48

I did some pointer jumping for the first time today and it is quiet interesting. If you don't have an array in e.g. a structure, but consecutive variables, you can just take a pointer and add some bytes to it to jump there, like in these functions:

Code:
BMAP** avViewRtRef (VIEW* v, int index)
{
	if (v == NULL || index < 0 || index >= 4)
		return NULL;
		
	if (index == 0)
		return &(v->bmap);
	else
		return &(v->target1) + (index - 1) * sizeof(BMAP*);
}

BMAP** avMtlSkinRef (MATERIAL* m, int index)
{
	if (m == NULL || index < 0 || index >= 4)
		return NULL;
		
	return &(m->skin1) + index * sizeof(BMAP*);
}



I wanted to have two functions that give me the pointer to the bitmap-pointers of the view render targets (bmap, target1, target2, target3) and the material skins (skin1, skin2, skin3, skin4). In the case of the material, all skins are after another (see struct material in atypes.h), but for views, target1...target3 are not directly in memory after bmap, therefore the if.

Essentially, you just take a pointer adress and add the size of the pointer times the fields you want to jump and voila, you have it.

The (non-efficient) alternative to this would be a switch...case, like this

Code:
BMAP** r = NULL;
	
switch (index)
{
	case 0: r = &(v->bmap); break;
	case 1: r = &(v->target1); break;
	case 2: r = &(v->target2); break;
	case 3: r = &(v->target3); break;
}		

return r;



Hm, I don't know if this is helpful but I feel motivated to share things since that good-bye post of Sid wink
Posted By: WretchedSid

Re: pointer jumping - 05/10/13 14:41

v->target1 + offset, no?

I don't know about the Lite-C compiler, but pointer arithmetic (not jumping ;)) doesn't work by adding bytes, unless you used bytes to begin with.

Code:
int *bar = xyz;
*(bar + 0) = 1024; // First element of the "Array"
*(bar + 1) = 512; // Second element
*(bar + 2) = 32; // Third element



Since the Lite-C compiler packs everything closely anyways (and a pointer is word aligned), target1, target2 and target3 are in fact consecutively laid out in memory, so adding 1 to target1 will result in a pointer pointing to target2.

Sooo...
Code:
if(offset == 0)
    return v->bmap;
return v->target1 + offset - 1;



Speaking of, you can use return inside a case label wink

Quote:
Hm, I don't know if this is helpful but I feel motivated to share things since that good-bye post of Sid wink

I hope I didn't stop you. I'm off again now anyways, I just clicked here out of old habit...
© 2024 lite-C Forums