What does " *Pointer++ = '\0' " mean?

Hi all!

I'm trying to figure out a code and I see in the source code : *hostpart++ = '\0'. What does it do? In the comment of the source code it says "Split username and hostname" but I can't see how this will do anything.

hostpart is a pointer to a buffer array, called 'buf' in the source code.

This line should have made me understand, but I don't know what 'index' means or does!
hostpart = index(buf, '@')

Can you help me? I'd really appreciate it.
Do you understand how post increment works? I'll give you a hint: the post increment operator has a higher precedence than the dereference operator.

As for 'index', it should be obvious that it gets the index of the given character in the given string.
Last edited on
I think that name index for the function is not a good name because the function as it is seen from the first your code snip return a pointer.

I would rewrite your code snips the following way

hostpart = index( buf, '@' );
*hostpart++ = '\0';

So the symbol '@' is replaced by '\0' and the pointer is moved to the next position in the buf after that symbol.

If buf has type char * or char [] then the same can be done with standard C function strchr

if ( char *p = strchr( buf, '@' ) ) { *p++ = '\0'; /* some other stuff with p */ }

As an example consider the following function that copies one character array into another

char * strcpy( char *dest, const char *source )
   char *p = dest;
   const char *q = source;

   while ( *p++ = *q++ );

   return ( dest );
Last edited on
To be specific, what the code does is as follows:
hostpart = index(buf, '@')

buf is, presumably, an array of characters, and hostpart is, presumably, a pointer to a char. This function call sets the value of hostpart such that it points to the location in memory of the first occurrence of the character '@' in buf.

*hostpart++ = '\0'

This does the following:

1) Changes the value at that location to be '\0'.
2) Increments hostpart, so that it now points to the character after the new '\0' in buf.

This effectively terminates the string held in buf where the '@' character used to be.

It also leaves hostpart pointing to the part of buf that was immediately after the '@'.

In other words, you now have 2 strings - one containing the part before where the '@' used to be, and one containing the part afterwards.

Personally, I dislike the needless packing of multiple operations onto one line like this. I'd have written it:

hostpart = index(buf, '@');
*hostpart = '\0';

(Edited, cause I screwed up the first time.)
Last edited on
Thanks a lot! I had some trouble understanding at first (I don't know much about C, I'm doing this for a personal project), but after reading two or three times... Now I get it. Thank you! ☺
Topic archived. No new replies allowed.