Re: A little help please
From: Jonathan Mcdougall (jonathanmcdougall_at_DELyahoo.ca)
Date: Tue, 28 Dec 2004 11:24:10 -0500
>>You don't need the cast.
> But according to the question if I read it correctly I do???
> The question is exactly as written to newsgroup.
You don't need an explicit cast to convert a
pointer type to void*. You *do* need to cast a
void* to another pointer type.
>>>arr += nBytes // increment by nBytes to get next element
>>That shows us you don't know how pointers work and that means you shouldn't
> ??? if arr points to first element of int array then I thought by
> incrementing the pointer by nBytes I was pointing to next array element.?
That works if the pointer has a known type, such
as int*. When doing pointer arithmetics, such as
increment and decrement, the pointer is moved
according the the type's size. On an
implementation where ints are 4 bytes, the pointer
would move by 4 bytes. If you try to do that on a
void pointer, how many bytes would the pointer
>>>int* i = &arrX; // set i as pointer to first element of array
>>>void * vp = static_cast<void*> (i); // convert i to a void*
>>You don't need that
> right now I am confused, the question states that I should cast the int
> array to a void* using a static cast.
First, you don't cast it to an array of void*, you
are casting it to a pointer to a void*.
Second, you don't need static_cast to cast an int*
to a void* (try it).
>>> // assign to vp
>>>func1( vp, sizeof( arrX ), 8 );
>>>for( int i = 0; i < 10; i++ )
>>Prefer ++i over i++.
> if I did ++i would this not make the start of loop start at 1 ?? since
> it increments before evaluating?
No, the increment is done at the same point, that
is, after the first execution of the loop, whether
you use ++i or i++. Do read about the difference
about postfix and prefix increment/decrement.
>>Your code is bound to be invalid. You'll have to assume a type (such as
>>char, as does memset()), ask the user for one or forget that function.
>>Templates are meant for this kind of problem.
> We have not covered such things yet, we have played with vectors but not
> templates yet.
And now you are playing with void pointers? What
kind of c++ class is that?
> I meant the only reason I could see for using a vcid* is for when you
> don't know the type to be assigned to a pointer so by declaring the
> pointer void* I can assign any type to it, but can't dereference a void*
> but instead have to cast it back to dereference it.
> For example
> void* vp;
> vp = &i;
> // *vp = 4 // can't do this can't dereference a void*
> // have to do this instead
> i = static_cast<int> (vp); // cast back to int*
You need a reinterpret_cast here.
> *i += 4; // i += 4 would make pointer point 4 ints further in memory?
Here is an example.
# include <iostream>
void increment_an_int(void *p, int by)
int *ip = reinterpret_cast<int*>(p);
*ip += by;
int my_int = 10;
std::cout << "before: " << my_int << std::endl;
std::cout << "after: " << my_int << std::endl;