Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to offset a pointer?

I want to pass a pointer to a function. I want this pointer to point to some place in the middle of an array. Say I have an array like such unsigned char BufferData[5000];, would the following statement be correct syntactically?

writeSECTOR( destAddress, (char *)( BufferData + (int)(i * 512 )) );
// destAddress is of type unsigned long
// writeSECTOR prototype: int writeSECTOR ( unsigned long a, char * p );
// i is an int
like image 774
PICyourBrain Avatar asked Oct 06 '10 13:10

PICyourBrain


People also ask

What is offset notation?

Offset binary, also referred to as excess-K, excess-N, excess-e, excess code or biased representation, is a method for signed number representation where a signed number n is represented by the bit pattern corresponding to the unsigned number n + K , K being the biasing value or offset.

Can pointer be subtracted?

The subtraction of two pointers is possible only when they have the same data type. The result is generated by calculating the difference between the addresses of the two pointers and calculating how many bits of data it is according to the pointer data type.


3 Answers

That would do, but just make it:

 writeSECTOR( destAddress, &BufferData[i * 512]);

(It sounds like writeSECTOR really should take an unsigned char* though)

like image 112
nos Avatar answered Oct 02 '22 03:10

nos


You can just do BufferData + i * 512. An arithmetic + operator on char* yields a char* when you add an integer value to it.

like image 24
reko_t Avatar answered Oct 02 '22 04:10

reko_t


Pointer arithmetic is fairly simple to understand. If you have a pointer to the first element of an array then p + 1 points to the second element and so on regardless of size of each element. So even if you had an array of ints, or an arbitrary structure MyData it would hold true.

MyData data[100];
MyData *p1 = data;;  // same as &data[0]
MyData *p2 = p1 + 1; // same as &data[1]
MyData *p3 = p2 + 1; // same as &data[2]
MyData *p4 = p2 - 1; // same as &data[0] again

If your array is unsigned char then you just add however many bytes offset you wish to go into the array, e.g.

unsigned char data[16384];
unsigned char *offset = data + 512; // same as &data[512]
*offset = 5; // same as data[512] = 5;

Alternatively if the notation is confusing, you can always refer to it as it is shown in comments above, e.g. &data[512]

like image 29
locka Avatar answered Oct 02 '22 02:10

locka