I'm looking through my textbook and I'm a little confused about some of the code that is in there. In one part, they are performing pointer arithmetic in the following way:
void* bp;
...
bp = (void*)((char*)(bp)+16);
...
but later on, they do the following:
void* bp;
...
bp = bp+16;
...
I feel like they should be two different things but they are treating it like the same thing. I feel this way because, for example, if you were to do an array access (for an integer array for example),you would do the following
int* a = malloc(n*sizeof(int));
...
q = *(a+1);
...
in this case, aren't I accessing the next 4 bytes in the integer array and not the next byte? Similarly, I feel that if I have void* a, then *(a+1) should be the next 4 bytes... Or is that not the case? Thank you.
An unsigned char* is a block of memory. A void* is either a block of raw memory or a pointer of unknown type into the above unsigned char* (or unknown type pointer is erasure situations)
Since void is an incomplete type, it is not an object type. Therefore it is not a valid operand to an addition operation. Therefore you cannot perform pointer arithmetic on a void pointer.
Why do we use a void pointer in C programs? We use the void pointers to overcome the issue of assigning separate values to different data types in a program. The pointer to void can be used in generic functions in C because it is capable of pointing to any data type.
void pointer in C / C++ A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typecasted to any type.
It's a slip-up. Arithmetic on void *
is not defined by the standard, but some compilers offer it as an extension, behaving the same as char *
for arithmetic. The second is formally not valid C, but slipped through presumably out of (bad) habit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With