dimanche 4 octobre 2020

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

I've been trying to create my own string using OPP, 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 function is a const 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 to get the values length(strlen) and copying the value(strcpy)?

The following code below worked:

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);
    }
}

Aucun commentaire:

Enregistrer un commentaire