I'm trying to write a function that will work out the length of two string char arrays, using pointer arithmetic. It seems to be working but I'm still getting used to pointers and addresses etc and would be grateful if you could let me know what you think. If possible could tell me if my understanding is correct in thinking that, when finding the length of a string char array, you're actually finding how many bytes it is? Thank you.
Here is the code:
#include <stdio.h> #include <stdlib.h> int cmpstr(const char *,const char *); int main() { const char hello[10] = "hello"; const char world[10] = "world"; printf("%d", cmpstr(hello, world)); return 0; } int cmpstr(const char *s1, const char *s2) { int start1 = s1; // start address for s1 string while(*s1 != '\0') { s1++; // increase address until the end } s1 = s1-start1; // subtract start address from end address int start2 = s2; // start address for s1 string while(*s2 != '\0') { s2++; // increase address until the end } s2 = s2-start2; // subtract start address from end address if(s1==s2) // if s1 string is equal to s2 string { return 0; } else if(s1>s2) // if s1 string is greater than s2 string { return 1; } else if(s1<s2) // if s1 string is less than s2 string { return -1; } }