memmove() is a libc function I always find myself making confusing calls to. Its prototype is in string.h, and it looks like this:

void *memmove(void *dest, const void *src, size_t nbytes);

This "moves" nbytes of src into dest. By "move", I mean copy, but unlike memcpy(), this function is written so that if nbytes of dest contains some of the same memory as nbytes of src, nothing is overwritten.

This makes a lot of things easier, like, say, taking item i out of (struct my_struct*)ptr:

	/* copy array_size-i-1 elements from ptr+i+1 to
	   ptr+i */
	memmove( ptr+i, ptr+i+1, (--array_size-i)*sizeof(struct my_struct) );
	/* lower allocation size */
	ptr = realloc( ptr, array_size*sizeof(struct my_struct) );
	assert( ptr != NULL );

Or, let's say you want to take whitespace out of a string...

	char *p = s-1;
	while( *++p )
		if( *p == ' ' || *p == '\t' ) {
			/* move the string back */
			memmove( p, p+1, strlen(p) );
			/* check p again; it's changed */
			--p;
		}

The function itself is from BSD, and is standard in ISO C.

Log in or register to write something here or to contact authors.