'Pointers - Strings
I have a code chunk which is quite meaningless for me. Is there someone can explain it to me?
Thanks
int strLength(char *str) {
char *p = str;
// Go until the end of the string
while (*p != ‘\0’)
p++;
return (p – str);
}
Firstly I dont get the idea behind return section of the code.
Secondly
char *p = str;
it didn't fit me perfectly
Thanks in Advance
Solution 1:[1]
The string is stored in memory sequentially, The idea is to find the character that ends the string (in C the accepted symbol is '\0'), you increment the pointer p until you find this symbol.
When you find '\0' , You substract between two addresses to find the length.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alon Vaisgur |
