الجمعة، مايو ٠٥، ٢٠٠٦

Pointers, again

el salamo 3alikom,

That's a good thing you could make with pointers,
u know, characters may be indexed either from -127 to 128 i think, or from 0-255
our dear friend has a written pseudo or scenario that index the first way,,, he doesn't wanna keep adding offset to convert it to the second way!
that's he wants:
array[-x] => returns some character

ok
do u have any idea about it ?

lets define the array:
char* ch = new char[256] //C++ Code;

//Till now we should start indexing from 0, other wise negative indexing may result in outOfRange or 'Access Violation'

resolve that by the coming trick:
ch += 127;

wow, now the pointer is pointing to the middle of the array, and the compiler has reserved a 256 bytes for ur array too,,,, it's complete now ;)

ch[-127] = '0';
kep addressing from -127 till 128

What about C# ?
u can do it:

char [] array = new char[256];
fixed ( char* ptr = &array[0])
{
char* p = ptr+127;
}

//ok, u may notice some changes,,, u couldn't increment the pointer itself, that's why we used another one 'p'
// the fixed thing,,, it's because u r taking the address of unfixed expression (the char array)

in C# , u may use -ve indexing even without shifting the pointer, but that ofcourse won't result the desired output :D

wish that was helpful
el salamo 3alikom wa ra7mato Allah

ليست هناك تعليقات: