In Java there is no pointer arithmetic. It think this is what you are asking about. For example, imagine that malloc
returns a pointer of type int
int* malloc(size_t size)
{
//
}
You would possibly receive the pointer, which is basically a pointer to an array
. Then you would index it like regular arrays.
int* arr = malloc(10); // 10 contiguous int(s).
The problem is that C
doesn't have functions overloading. So, we have to find a way to write a generic malloc
. Otherwise, you would end up with a different malloc
for every type. The solution, is to send the required number of bytes that you need. Then, you can index it however you like. This gives a greater flexibility and one for all solution.
int* i = (int*)malloc(10); // 40 bytes if int = 4 bytes
char* c = (char*)malloc(10); // 10 bytes if char = 1 byte
int thirdElement = i[3]; // third element. 12 bytes away from (*i)
char secondElement = c[2]; // second element. 2 bytes away from (*c)
So, the whole idea is that it doesn't matter how we index the memory we got from malloc
. All what we have to do is to specify the type of the newly created array to index it properly. void*
means that this is a pointer to place in memory that we haven't specified how to index.