为什么不必使用 strcpy 和 strlen 取消引用指针?

Why don't you have to dereference a pointer using strcpy and strlen?

我一直在尝试创建自己的字符串 class,但我 运行 遇到了以下代码的问题:

String::String(const char *s) : str {nullptr}
{
    if(s == nullptr)
    {
        str = new char[1];
        *str = '[=10=]';
    }else{
        str = new char[std::strlen(*s)+1];
        strcpy(*str,*s);
    }
}

我传入构造函数的是一个const char指针;要获取指针内的值,我必须取消引用它,对吗?但是,为什么在将参数放入 strcpy 和 strlen 时不必取消引用指针?

如下所示。

String::String(const char *s) : str {nullptr}
{
    if(s == nullptr)
    {
        str = new char[1];
        *str = '[=11=]';
    }else{
        str = new char[std::strlen(s)+1];
        strcpy(str,s);
    }
}
str = new char[std::strlen(*s)+1];

what I passed into the function is a const pointer

不,那不是你通过的。您传递给函数的是 charchar 不是指针。

to get to the value inside the pointer I have to dereference it right?

当您有指向 char 的指针时,要获得指向的 char,您必须间接通过指针。但是 std::strlen 不期望 char 作为参数,所以 char 不是你需要的,因此你不需要通过指针间接获得 char.

std::strlen的参数是指向char的指针。所以,如果你有一个指向 char 的指针,并且你需要将一个指向 char 的指针传递给函数,那么你需要对指向 char 的指针做些什么才能得到一个可以传递给函数的指向 char 的指针?您什么都不用做,因为您已经有了一个指向 char 的指针,您可以将其传递给函数(假设该值满足函数的 pre-conditions)。

你必须传递字符串的开头地址,字符串本质上是一个non-zero字节的序列。最简单的 strlen 看起来像:

size_t strlen(const char* s)
{
    const char* p = s;
    
    while(*p) p++;
    return p - s;
}

实际实现通常通过使用直接汇编代码检查长字 and/or 来进行一些优化,这比逐字节扫描内存具有更好的性能。在不知道字符地址的情况下,这是无法完成的,尤其是在不存在引用的 C 中。

strcpystrlen 都有 char * 作为参数,因此您不需要考虑。

更多信息: https://www.cplusplus.com/reference/cstring/strcpy/

https://www.cplusplus.com/reference/cstring/strlen/