【发布时间】:2010-02-12 09:13:25
【问题描述】:
我试图在一个函数调用中创建一个连续的内存块,该函数调用将内存的第一部分作为指向其他块的指针数组。基本上,我正在尝试这样做:
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);
}
但只有一个街区。这是据我所知:
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);
}
【问题讨论】: