I'm a beginner in C and I'm facing this problem: I created a function based on the fast matrix allocation method (Oliveira and Stewart, "Writing Scientific Software", pag. 94) and I want to use it for any data type. I therefore changed it a bit as follows:
void ** malloc_array2d(size_t m, size_t n){
/* pointer to array of pointers */
void ** pointer;
size_t i;
/* allocate pointer array of length m */
pointer = malloc(m*sizeof(void));
if(pointer == NULL){
return NULL;
}
/* allocate storage for m*n entries */
pointer[0] = malloc(m*n*sizeof(void));
if (pointer[0] == NULL) {
free(pointer);
return NULL;
}
/* set the pointers */
for (i = 1; i < m; i++) {
pointer[i] = pointer[0] + i*n;
}
return pointer;
}
but I get segmentation fault.
The question is: how to allow for memory allocation of different data type, since sizeof(void) is not working (and indeed it returns just 1)? Any feedback is really appreciated. Thanks.