Reputation: 29326
char *start = str;
char *end = start + strlen(str) - 1; /* -1 for \0 */
char temp;
How does that find the end of the string? If the string is giraffe
, start
holds that string, then you have:
char *end = "giraffe" + 7 - 1;
How does that give you the last char in giraffe? (e
)
Upvotes: 0
Views: 87
Reputation: 361917
Here's how "giraffe"
is laid out in memory, with each number giving that character's index.
g i r a f f e \0
0 1 2 3 4 5 6 7
The last character e
is at index 6. str + 6
, alternatively written as &str[6]
, yields address of the last character. This is the address of the last character, not the character itself. To get the character you need to dereference that address, so *(str + 6)
or str[6]
(add a *
, or remove the &
).
In English, here are various ways to access parts of the string:
str == str + 0 == &str[0] address of character at index 0
== str + 6 == &str[6] address of character at index 6
*str == *(str + 0) == str[0] character at index 0 ('g')
== *(str + 6) == str[6] character at index 6 ('e')
Upvotes: 8
Reputation: 155
There is no string
type in C, just char
, and arrays of char
.
I would tell you to google "c strings", but since that's apparently a term that you need safesearch for these days, here's a link: http://www.cprogramming.com/tutorial/lesson9.html
Upvotes: 1
Reputation: 141887
If the string is giraffe, start holds that string
Not exactly, start
is a char *
, so it holds a pointer, not a string. It points to the first character of "giraffe": g
.
start + 1
is also a char *
pointer and it points to the next element of size char
, in this case the i
.
start + 5
is a pointer to the second f
.
start + 6
is a pointer to the e
.
start + 7
is a pointer to the special character \0
or NUL, which denotes the end of a string in C.
Upvotes: 3
Reputation: 220
start is a pointer to the string "giraffe" in memory, not the string itself.
Likewise end is a pointer to the start of the string + 7 bytes (minus one to account for the null terminator).
Upvotes: 2