robot bath
robot bath

Reputation: 11

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

Upvotes: 0

Views: 61

Answers (3)

John Kugelman
John Kugelman

Reputation: 361585

*(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';
}

Upvotes: 2

mcleod_ideafix
mcleod_ideafix

Reputation: 11418

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

Upvotes: 0

kdopen
kdopen

Reputation: 8215

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';

Upvotes: 0

Related Questions