连续的内存块的动态分配(malloc的) [英] Dynamic allocation (malloc) of contiguous block of memory
问题描述
有关的转让,我不得不分配一个连续的内存块的结构,但我第一次尝试使用整数第一的二维数组做到这一点,看看我是否理解正确。我们在这对指针阵列(行)产生的存储器的块,然后初始化cols和指向指针给他们的书的例子。这个例子是:
For an assignment, I have to allocate a contiguous block of memory for a struct, but I'm first trying to do it with a 2D array of ints first and see if I understand it correctly. We had an example in the book that creates a block of memory for the pointer array (rows), and then initializes the cols and points the pointer to them. This example was:
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);
}
基本上,我需要做上述code确实只是让一个内存连续块的东西。约束是我只允许一次调用malloc,然后我不得不使用指针数学知道的指针初始化。所以,我想我会初始化内存不够用是这样的:
I basically need to do what the above code does except make it one contiguous block of memory. The constraint is I'm only allowed to call malloc once, and then I have to use pointer math to know what to initialize the pointers to. So I thought I would initialize enough memory with something like:
int *createInt2D(size_t rows, size_t cols)
{
malloc(rows * sizeof(int *) + (row + cols) * sizeof(int));
}
但是,这似乎并不完全正确,因为我想我将不得不类型转换的void *从malloc返回,但它是int和int的组合*。所以,我不太肯定我是否在正确的轨道上。思考?
But that doesn't seem quite right since I would think I would have to typecast the void * returned from malloc, but it's a combination of int and int*. So I'm not quite sure if I'm on the right track. Thoughts?
推荐答案
如果你想有一个连续的数组,你应该的malloc(行* COLS *的sizeof(INT))
If you want a contiguous array, you should malloc(rows * cols * sizeof(int))
.
然后你访问改编[X,Y]
这样的:
arr[x * cols + y]
这篇关于连续的内存块的动态分配(malloc的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!