简体   繁体   中英

How does C evaluate this expression? C pointers

I don't fully understand this, could someone help me evaluate the expression below? If message has ** and length only has * , by using *() are we dereferencing to *message and length ? Any help would be much appreciated.

    bool func(char** message, size_t* length)
    {
       *(*message + *length) = '\0';
    }

*(a + b) is another way of writing a[b] . The statement above is equivalent to

(*message)[*length] = '\0';

*message is a char* string, and *length is a size. It sets the character at index *length to NUL.

There is no particular reason for the extra layer of pointers. It would be more normal to remove one * from each parameter and have the function be:

bool func(char* message, size_t length)
{
   *(message + length) = '\0';
}

Or, in other words,

bool func(char* message, size_t length)
{
   message[length] = '\0';
}

the part inside the parentheses calculates an address, and then the NUL is stored at that address.

Let's unpack it

char *ptr = *message; // derefernce the pointer to pointer
size_t len = *length; // get the length by derefencing the pointer
char * new_ptr = ptr + len;
*new_ptr = '\0';

message is a pointer to a pointer to a block of bytes (a string actually). length is a pointer to a size_t (some kind of non negative integer). The expression is decoded as follows:

*message is a pointer to the string

*length is a number, the value at which length is pointing at, probably the required length for the string, or the length at which the string will be truncated (judging from the whole expression behaviour)

*message + *length is in aritmethic pointer, a pointer that points to some location which is *length bytes away from the start of the string

*(*message + *length) is dereferencing the pointer. This is the actual character we are pointing at.

*(*message + *length) = '\\0' This is storing a NUL byte at that location, thus, terminating the string.

The function could be rewritten as this, to improve readability:

bool func(char** message, size_t* length)
{
   size_t len = *length;
   char *msg = *message;

   msg[len] = '\0';
}

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