Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void* vs. char* pointer arithmetic

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.

like image 822
de1337ed Avatar asked Apr 07 '12 20:04

de1337ed


People also ask

Is a char * a void *?

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)

Why can't we perform arithmetic on a void * pointer?

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.

What is the advantage of void pointer in C?

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.

What is a void * in C?

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.


1 Answers

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.

like image 73
Daniel Fischer Avatar answered Oct 06 '22 02:10

Daniel Fischer