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
Answer: A pointer contains an address . That address can come from anywhere. A string is a NUL-terminated array of characters.
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' .
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.
Just
length = end - start;
without ampersands and casts. C pointer arithmetics allows this operation.
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);
}
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