void * unknown size error in C

How to fix this error?

1
2
3
4
5
6
7
8
9
10
11
12
/* Data structure for Vector */
typedef struct
{
	void* pvElement;	/* the pointer to elements */
	size_t iSizeElement;/* the size of element */
	int iNumElement;	/* the number of elements (user's view) */
	int iNumAlloc;		/* the number of allocated elements (system's view) */
} Vector;

/* error C2036: 'void *' : unknown size occurs in line 12th */
for (i = 0; i <= (v->iNumElement) - 1; i++)
    memcpy((char*)&(newV->pvElement[i]), (char*)&(v->pvElement[i]), (size_t)v->iSizeElement);

Thank you!!
Someone says I can try it like:

1
2
for (i = 0; i <= (v->iNumElement) - 1; i++)
	memcpy(&(((char*)newV->pvElement)[i - 1]), &(((char*)v->pvElement)[i]), (size_t)newV->iSizeElement);


Is it right? No compiling error of this code but I'm not sure.
Last edited on
Are you just shifting all the array values backward by 1 element.
By this I mean that if your array values looked something like this

1 2 3 4 5

you will end up with (the element at the font gets effectively discarded?)
2 3 4 5 5
Last edited on
You cannot use [] in a pointer of type void* because the size of the element pointed to by the pointer is unknown. You must cast the pointer pvElement into a data type before attempting this.

So yes, ((char*)v->pvElement)[i] works but that is not all. i is not the ith element, but the ith byte. You need to do ((char*)v->pvElement)[i * v->iSizeElement] to really get a pointer to the first byte of the ith element.
Last edited on
What I want to say is that to move x consective elements is a loop like this is pretty naff.
He knows the size of the element - so to move x consecutive elements:

1. Calculate the destination address - once.

2. Calculate source address - once.

3. Calulate number of bytes to move - once.

4. Call memcpy function - once
Topic archived. No new replies allowed.