I have come across a C code similar to the following:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = malloc(200*sizeof(int));
int i;
for (i = 0; i < 200; i++)
{
a[i] = i;
}
int (*b)[10] = (void*) a;
printf("\nsizeof(int):\t%d\n", sizeof(int));
printf("\nb[0]:\t%d\n", b[0]);
printf("\na:\t%d\n", a);
printf("\nb[19]:\t%d\n", b[19]);
printf("\na+190:\t%d\n", a+190);
printf("\nb[0][8]:\t%d\n", b[0][8]);
printf("\nb[19][9]:\t%d\n", b[19][9]);
return 0;
}
As per my understanding, the line int (*b)[10] = (void*) a; is trying to assign pointer b (which is supposed to point to an array of 10 integers) to the starting address of array a typecast as a void pointer. I would have expected b[i] to hold the same data as a[i] for i=0..9 (and any index other than 0 to 9 for b resulting in some undefined behavior). However, the program produces outputs similar to the following sample:
sizeof(int): 4
b[0]: 9768976
a: 9768976
b[19]: 9769736
a+190: 9769736
b[0][8]: 8
b[19][9]: 199
Clearly, b has become an array of 20 pointers, with each elemental pointer pointing to a unique portion of the a array corresponding to 10 integers (or 40 bytes) each. Can someone please explain what exactly int (*b)[10] = (void*) a; does? Specifically, how does the typecast (void *) help in distributing the entire a across multiple elements of b? The above code would not compile without the (void *) cast.
int *b = (void *)a;would only be able to access oneint?b[0]is an array consisting of the first 10 ints,b[1]is the next 10 ints, and so onint (*b)[10] = (void*) a;statement. I could not find other such examples in my online searches. This seems like a way of creating separate pointers for chunks of a large array, something I have not come across earlier.int *b = (void *)aexcept you are pointing to 10 ints instead of pointing to 1 int.