views:

316

answers:

4

Hi, I ran into a little problem and need some help:

If I have an allocated buffer of chars and I have a start and end points that are somewhere inside this buffer and I want the length between these two point, how can I find it?

i.e

char * buf; //malloc of 100 chars
char * start; // some point in buff
char * end; // some point after start in buf

int length = &end-&start? or &start-&end? 
//How to grab the length between these two points.

Thanks

+4  A: 

It is just the later pointer minus the earlier pointer.

int length = end - start;

Verification and sample code below:

int main(int argc, char* argv[])
{
    char buffer[] = "Its a small world after all";
    char* start = buffer+6;  // "s" in SMALL
    char* end   = buffer+16; // "d" in WORLD

    int length = end - start;

    printf("Start is: %c\n", *start);
    printf("End is: %c\n", *end);
    printf("Length is: %d\n", length);
}
abelenky
You don't need to cast to int - it is very dangerous, because int is signed so you will end up doing math with two signed ints rather then pointers and result may differ from what you expect.
qrdl
I don't think qrdl is right. Two signed ints? Which two signed ints? The cast is being made to the result of the subtraction, not the two pointers that are being subtracted. The result of pointer subtraction is signed, quite properly. If end actually comes before start, then the result should be negative, right?
Bill Forster
+16  A: 

Just

length = end - start;

without ampersands and casts. C pointer arithmetics allows this operation.

qrdl
James
Because that's what you do when you're new to C. Just add a star or an ampersand and hope it works this time. :-) Hang in there, you'll get it.
Thomas
I never did that. But I guess that was because I had prior experience with peek() and poke().
Artelius
A: 

simply

int length = (int)(end - start);
klez
+1  A: 

There's even a type, ptrdiff_t, which exists to hold such a length. It's provided by 'stddef.h'

eloj