gpt4 book ai didi

使用 malloc 的连续内存块

转载 作者:太空宇宙 更新时间:2023-11-04 03:08:05 25 4
gpt4 key购买 nike

我试图在一个函数调用中创建一个连续的内存块,该函数调用将内存的第一部分作为指向其他 block 的指针数组。基本上,我想做的是:

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);
}

最佳答案

像这样

 int **Create2D(size_t rows, size_t cols) 
{
size_t cb = (rows * sizeof(int *)) + (rows * cols * sizeof(int));
int * pmem = (int *)SafeMalloc(cb);

int ** prows = (int **)pmem;
int * pcol = (int *)&prows[rows]; // point pcol after the last row pointer

for (int ii = 0; ii < rows; ++ii)
{
prows[ii] = pcol;
pcol += cols;
}

return prows;
}

关于使用 malloc 的连续内存块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2250675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com