1

I tried to write my function like "memcpy" in C to copy a block of data from a source address to a destination address.

In line *dst_addr++ = *src_addr++;, the error is appeared: "invalid use of void expression"

The function I wrote:

void MemCpy(void *src_addr, void *dst_addr, int length)                
{
    while(length--)
    {
        // copy by single byte
        *dst_addr++ = *src_addr++;
    }

    return dst_addr;
}

I used void to point to any object type if i need it later.

Why did I use the "void" wrong? Could someone explain my mistake?

wovano
  • 4,543
  • 5
  • 22
  • 49
  • 3
    Type `void` has no size. You must cast to some other pointer type like `char*` if you want to access the memory. GCC includes an extension that allowes pointer arithmetics with `void*` but dereferencing will not work with GCC either. – Gerhardh Sep 08 '21 at 07:32
  • 2
    NB: Why `return dst_addr` for a `void` function? – wovano Sep 08 '21 at 07:48

2 Answers2

1

There are two problems in your code:

  • void has no size and you cannot dereference void pointers nor perform pointer arithmetic on them
  • you forgot the * in void *MemCpy(...

Correct code:

void *MemCpy(void *src_addr, const void *dst_addr, size_t length)
{
  const char *s = src_addr;
  char *d = dst_addr;

  while (length--)
    *d++ = *s++;

  return dst_addr;
}

BTW in the original memcpy, the first parameter is the destination pointer, so your MemCpy function is not quite the same as the original memcpy.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
0

You cannot perform pointer arithmetics over void*. You have to cast to appropriate type.