I'm trying to create a contiguous block of memory in one function call that has the first part of the memory as pointer arrays to the other blocks. Basically, I'm trying to do:
int **CreateInt2D(size_t rows, size_t cols)
{
int **p, **p1, **end;
p = (int **)SafeMalloc(rows * sizeof(int *));
cols *= sizeof(int);
for (end = p + rows, p1 = p; p1 < end; ++p1)
*p1 = (int *)SafeMalloc(cols);
return(p);
}
void *SafeMalloc(size_t size)
{
void *vp;
if ((vp = malloc(size)) == NULL) {
fputs("Out of mem", stderr);
exit(EXIT_FAILURE);
}
return(vp);
}
But with one block. This is as far as I've gotten:
int *Create2D(size_t rows, size_t cols) {
int **memBlock;
int **arrayPtr;
int loopCount;
memBlock = (int **)malloc(rows * sizeof(int *) + rows * cols * sizeof(int));
if (arrayPtr == NULL) {
printf("Failed to allocate space, exiting...");
exit(EXIT_FAILURE);
}
for (loopCount = 1; loopCount <= (int)rows; loopCount++) {
arrayPtr = memBlock + (loopCount * sizeof(int *));
//I don't think this part is right. do I need something like arrayPtr[loopCount] = ....
}
return(memBlock);
}