我重写了 strlen()
来自 <string.h>
的函数 header 。
使用下面的代码调用该函数会产生一个高得离谱的数字,例如6356735
#include <stdio.h>
#include <string.h>
size_t my_strlen(const char *s);
int main(void) {
const char str[] = "abcd";
printf("length of abcd: %d\n", my_strlen(str));
}
size_t my_strlen(const char *s) {
const char *p = s;
while (*s)
s++;
return s;
}
更改 my_strlen
的返回语句至 return s - p;
给出正确的字符串长度。
如果我没记错的话,p
指向字符串的开头,所以减去 p
来自 s
应与 s
相同?这具体是如何工作的?
最佳答案
在这里,您返回的是字符串(指向 char
的指针)而不是字符串的长度:
size_t my_strlen(const char *s)
{
const char *p = s;
while(*s)
s++;
return s; // here
}
相反,这样做(从开头减去字符串的末尾):
size_t my_strlen(const char *s)
{
const char *p = s;
while(*s)
s++;
return s-p; // here
}
字符串不存储在零位置,它们存储在内存中的某个位置(某个位置不为零,取决于环境)。
例如,取这个:char *p1 = "helloworld"; char *p2 = "再见"; p1 = p2 + 5;
。 p1
没有指向 world
,它指向 ye
。
关于关于返回字符串长度的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57446441/