I made a function to create a contiguous two dimensional array like this:
void** create2DArray(int row, int col, size_t s) {
void *pool = malloc(s * row * col);
void **array = malloc(s * row);
if(pool==NULL || array==NULL) return NULL;
for(int i=0;i<row;i++) {
array[i] = pool + i * col * s;
}
return array;
}
The function above used like this:
int **edge_matrix = create2DArray(num_vertices, num_vertices, sizeof(int));
It works without problem. But one day, I thought that I made a mistake, and I changed a line of the code with this:
array[i * s] = pool + i * col * s;
Due to the pointer arithmetic rule, the void* will always increase by i * 1 byte. I changed it so it will increase by i * s byte like usual pointer arithmetic for non void* type. But why the first one works while the second one doesn't?