Search code examples
c++pointersfunction-pointers

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


I've been trying to create my own string class, but I ran into a problem with the following code below:

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

What I passed into the constructor is a const char pointer; to get to the value inside the pointer I have to dereference it right? But why don't you have to dereference the pointer when putting arguments into strcpy and strlen?

Shown below.

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

Solution

  • Both strcpy and strlen have char * as parameters therefore you would not need to deference.

    More information: https://www.cplusplus.com/reference/cstring/strcpy/

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