robot bath robot bath - 22 days ago 7
C Question

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

Answer

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