views:

113

answers:

7

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
+5  A: 

That would do, but just make it:

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

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

nos
A: 

That should work. In C, adding an integer to a pointer increases the pointer by the integer multiplied by the sizeof the type the pointer points to.

Nathan Fellman
+4  A: 

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

reko_t
A: 

it looks ok, but try it on the compiler,

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

Jose
A: 

That looks like it will pass in the address of the i*512'th element of the array. Is that what you want it to do?

I don't really see what that cast to int is buying you though.

T.E.D.
+1  A: 

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[1] 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]

locka
A: 

That should work as you think. Pointer in C is just an address in RAM,so you could drift the pointer in your measure.

shenju