Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String length between pointers

Tags:

c

char

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

like image 316
James Avatar asked Jul 06 '09 13:07

James


People also ask

What is the relationship between pointers and strings?

Answer: A pointer contains an address . That address can come from anywhere. A string is a NUL-terminated array of characters.

Does strlen work on pointers?

The strlen() FunctionThe strlen() accepts an argument of type pointer to char or (char*) , so you can either pass a string literal or an array of characters. It returns the number of characters in the string excluding the null character '\0' .

Can we use strlen in character array?

strlen() accepts a pointer to an array as argument and walks through memory at run time from the address we give it looking for a NULL character and counts up how many memory locations it passed before it finds one. The main task of strlen() is to count the length of an array or string.


2 Answers

Just

length = end - start;

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

like image 51
qrdl Avatar answered Oct 04 '22 06:10

qrdl


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);
}
like image 28
abelenky Avatar answered Oct 04 '22 04:10

abelenky