Ohad Shamir
Ohad Shamir

Reputation: 37

Assignment from void pointer to another void pointer

I want to copy the bits from one void * to another void *.

How can I do it?

I tried this:

static void* copyBlock(void* ptr) {
    if (!ptr) {
        return NULL;
    }
    int sizeOfBlock=*(int*)ptr+13;
    void* copy = malloc(sizeOfBlock);
    if (!copy) {
        return NULL;
    }
    for(int i=0;i<sizeOfBlock;i++){
        *(copy+i)=*(ptr+i);
    }
    return copy;
}

but I get: invalid use of void expression

Upvotes: 1

Views: 7739

Answers (3)

D G
D G

Reputation: 869

You should use the memcpy function:

memcpy(copy, ptr, sizeOfBlock);

Depending on the compiler settings (you may be compiling as C++ and not as C), you may need to cast the pointers to a char pointer:

memcpy((char *) copy, (const char *) ptr, sizeOfBlock);

Note: The parameter of the function should be const char *ptr, to make sure you don't change the contents of ptr by mistake.

Upvotes: 0

Clifford
Clifford

Reputation: 93466

You cannot dereference, perform pointer arithmetic, indexing a void pointer because it has no base type or object size. You must therefore cast the void pointer to the a pointer to the type of the data units you are copying so that the compiler will know the size of the data to copy.

All that said, you'd be better off using:

memcpy( copy, prt, sizeOfBlock ) ;

Upvotes: 3

HolyBlackCat
HolyBlackCat

Reputation: 96053

This design (storing block size inside of a block without any struct) seems dangerous to me, but I still know the answer.

*(copy+i)=*(ptr+i);

Here you get the error, because you can't dereference a void pointer. You need to cast it to pointer to something before. Like this:

((char *)copy)[i] = ((char *)ptr)[i];

Upvotes: 2

Related Questions