void* assignment error

There's an error about the void type. @_@
The first run-time error occurs in the pushBack() (line 20 or 23, I'm not sure) when I try to copy the first value for v->pvElement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/* Data structure */
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;

/* some other code here... */

/* One operation function : Add new element in the end of list */
void pushBack(Vector* v, void* elem) /* debugging */
{	
    Vector* newV;
    int i;

    if (empty(v))
    {	
        v->pvElement = (void*) calloc(1, v->iSizeElement);
	v->iNumElement = 1;
	v->iNumAlloc = 1;
	memcpy((char*)&(v->pvElement), (char*)&elem, (size_t)v->iSizeElement);
    }
    else
    {	
	newV = (Vector*) calloc(1, sizeof(Vector));
	initialize(newV, v->iSizeElement);
	newV->pvElement = calloc((v->iNumElement) + 1, v->iSizeElement);
	newV->iNumElement = (v->iNumElement) + 1;
	newV->iNumAlloc = (v->iNumElement) + 1;
	/* copy previous vector */
	for (i = 0; i <= (v->iNumElement) - 1; i++)
            memcpy(&(((char*)newV->pvElement)[i * v->iSizeElement]), &(((char*)v->pvElement)[i * v->iSizeElement]), (size_t)v->iSizeElement);
	/* add the new component */
	memcpy(&(((char*)newV->pvElement)[((newV->iNumElement) - 1) * v->iSizeElement]), (char*)&elem, (size_t)v->iSizeElement);
	finalize(v);
	v = newV;
    }
}

/* some other code here... */

/* Invoking the pushBack() function */
void main()
{
    Vector v;
    int i;

    initialize(&v, sizeof(int));
    for (i = 0; i < 5; i++)
        pushBack(&v, &i);
}

closed account (zb0S216C)
dynamiclc wrote:
There's an error about the void type.

What's the error you're getting?

Wazzak
Last edited on
Line 23 is incorrect. It should be:

memcpy(v->pvElement, elem, v->iSizeElement);

You already have the pointers to the data, so no need to get the address of the pointers.

The else part is not correct either for the same reason. Besides, you don't need to copy one element at a time. The arrays are big, unbroken blocks of memory that can be copied at once in a single memcpy() call.

memcpy(newV->pvElement, v->pvElement, v->iSizeElement * v->iNumElement);

The above copies the entire array.

Finally, line 38 is a waste of CPU since v is just a copy of the pointer. Want to return a new array? You need to get a pointer to a pointer to a vector, not just a pointer to a vector.

Finally 2: Instead of returning (or trying to, at least, because you are not being successful) a new vector, just exchange the pvElement pointer with the new pointer.
Topic archived. No new replies allowed.