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
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.
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.
That would do, but just make it:
writeSECTOR( destAddress, &BufferData[i * 512]);
(It sounds like writeSECTOR really should take an unsigned char* though)
You can just do BufferData + i * 512
. An arithmetic +
operator on char* yields a char* when you add an integer value to it.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With