Advertisement

Advancing pointers

Started by May 25, 2000 06:09 PM
8 comments, last by OreoBoy03 24 years, 7 months ago
Hey, if I have a pointer like this: void *pPointer = new char[10]; How do i advance pPointer by 4 bytes so that it points to the 4th or 5th byte in my 10 byte sequence? Thanks
pPointer += 4;

You''ll have to cast the ptr from void though.

pPointer as a char, pPointer += 4 means advance 4 bytes.

pPointer as an int, pPointer += 4 means advance 16 bytes, since sizeof(int) == 4.

or go like this, pPointer[4], after casting of course. THat would give you the 4th element, not necesarily the 4th byte
"The Gates of Pearl have turned to gold, it seems you've lost your way."
Advertisement
I would do it like this and only if I didnt know in advance how many char I would need:

char *buffer = new char [buffer_size];

then to access it you can do buffer[4] if you need this to be void* you can just cast it when you pass it to the function.


Rick
You can''t do pointer arithmetic on void* because the size of the pointer is unknown.

If you make the pointer a char* both of the other suggests will work
Which leads me to my next question. Why is the hell does my compiler always say the size of a void* is unknown. The friggin'' sizeof operator tells me 4 bytes, isn''t that enough??? I''m not even worried about the value at the void*, I just want to move the physical pointer!!! If you get what I''m after, I''d really like a good reply. Thanks
Well, as for the sizeof thing...

sizeof(void*) is actually saying:
sizeof(NULL) which is actually saying:
sizeof(0) which is an INT. 4 bytes.

Disclaimer: This is what I THINK to be the case!

Advertisement
OreoBoy03
Actually sizeof (void*) equals 4, because you are asking the compiler to give you the size of a standard pointer.
A regular pointer is almost always going to be four bytes in size, because as a pointer, it holds the address of another variable.
The reason you cannot use pointer arithmatic on void pointers, is because the void pointer has an unresolved type associated with the address. Therefore, for example pointer++ will work for most types of pointers, because the item the pointer points to has a defined type. But a void pointer can point to anything. There is no way to do any operations on an undefined type.

So to increment a pointer, either make the pointer, a pointer to a valid type: int, char, struct, class, function, etc...

Or declare a void pointer, but cast it when used.
Thanks guys, I got it now.
Here is a tid-bit:
If you point at a public member of a class, which
is declared after a private member of a class,
by backing the pointer up, you can point at the private
member (at least back in the days of TC++). Wow,
I bet everyone here that reads that will use this
fine knowledge!
How do you make a pointer point a member function of a class though?

Possibility

This topic is closed to new replies.

Advertisement