char *start = str;
char *end = start + strlen(str) - 1; /* -1 for \0 */
char temp;
Run Code Online (Sandbox Code Playgroud)
如何找到字符串的结尾?如果字符串是giraffe,start持有该字符串,那么你有:
char *end = "giraffe" + 7 - 1;
这怎么会给你长颈鹿的最后一个字符?(e)
这是如何"giraffe"在内存中布局,每个数字给出该角色的索引.
g i r a f f e \0
0 1 2 3 4 5 6 7
Run Code Online (Sandbox Code Playgroud)
最后一个字符e在索引6处str + 6,或者写为&str[6],产生最后一个字符的地址.这是最后一个字符的地址,而不是字符本身.要获取您需要取消引用该地址的角色,*(str + 6)或者str[6](添加*或删除&).
在英语中,以下是访问字符串部分的各种方法:
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')
Run Code Online (Sandbox Code Playgroud)