Reputation: 107
I don't understand the last line of sstrlen, return t-str;
.
str
points to "my string"
and t
points to \0
so why does it work?
#include <stdio.h>
size_t sstrlen(char *str){
char *t = str;
for(;*t != '\0';t++);
return t-str; // how does it work?
}
int main()
{
char *str = "my string";
printf("%zu",sstrlen(str));
return 0;
}
Upvotes: 0
Views: 322
Reputation: 97
That is used to know the length of the string... Because of while loop t will go to the end of string or character array, and when you subtract ending address with starting address you will get string length. It's a bit faster then using index.
Upvotes: 0
Reputation: 20901
sizeof(char)
is defined to always be 1
. From C99:
When applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.
Assume that your m
character of my string
is stored at a memory location which is 100
. Arrays are always consecutive.
100 --> m <-- t and str point to here
101 --> y
102 --> (space)
103 --> s
104 --> t
105 --> r
106 --> i
107 --> n
108 --> g
109 --> \0 <-- end of for loop t points to here
Subtraction address 100
pointed to by str
from address 109
pointed to by t
results in 9
. That's how it works.
Upvotes: 5