James
James

Reputation: 3752

String length between pointers

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

Upvotes: 10

Views: 8386

Answers (4)

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

This C statement will calculate the difference between end and start. Simply:

int length = (int)(end - start);

Upvotes: 0

eloj
eloj

Reputation: 556

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

Upvotes: 1

abelenky
abelenky

Reputation: 64682

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);
}

Upvotes: 8

qrdl
qrdl

Reputation: 34968

Just

length = end - start;

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

Upvotes: 27

Related Questions