简体   繁体   中英

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

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/

str = new char[std::strlen(*s)+1];

what I passed into the function is a const pointer

No, that's not what you passed. What you passed into the function is a char . char is not a pointer.

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

When you have a pointer to char , then to get the pointed char you do have to indirect through the pointer. But std::strlen does not expect a char as an argument, so a char is not what you need and thus you don't need to indirect through the pointer which would get you a char .

The argument of std::strlen is a pointer to char . So, if you have a pointer to char , and you need to pass a pointer to char into the function, then what do you need to do to your pointer to char in order to get a pointer to char that could be passed into the function? You need to do nothing, because you already have a pointer to char which is what you can pass into the function (assuming the value satisfies the pre-conditions of the function).

You have to pass address of string's beginning, and string is essentially a sequence of non-zero bytes. A simplest strlen looks like:

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

Real implementations usually do some optimization by checking long words and/or using direct assembler code which results in better performance than scanning memory byte by byte. Without knowing the address of character, it cannot be done, especially in C where references didn't exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM