正确的方法来分配和指针的免费阵列阵列 [英] Correct way to allocate and free arrays of pointers to arrays
问题描述
我想创建一个指针数组的3浮标阵列。什么是做到这一点的正确方法?
I want to create an array of pointers to arrays of 3 floats. What is the correct way to do this?
float *array1[SIZE]; // I think it is automatically allocated
// OR
float **array1 = calloc(SIZE, sizeof(float*));
free(array1);
for (int i = 0; i < SIZE; i++) {
array1[i] = (float[]){0,0,0};
// OR
array1[i] = calloc(3, sizeof(float));
}
然后我将如何释放数据?我是pretty肯定只是免费(数组1);
是行不通的,所以我会释放阵列中的每个指针,然后释放磁盘阵列,因为我分配3辆彩车,我将释放每个浮点,则每3 float数组,那么整个阵列???
Then how would I free the data? I'm pretty sure just free(array1);
wouldn't work, so would I free each pointer in the array then free the array, or since I allocated three floats, would I free each float, then each 3 float array, then the whole array???
推荐答案
一个一般的规则是,每次调用时间的malloc()
或释放calloc()
你需要做返回的指针免费()
呼叫
A general rule is that for each time you call malloc()
or calloc()
you will need to do a free()
call on the returned pointer.
如果您希望编译时已知大小的二维数组,只需用一个二维数组! 浮VAL [5] [3]
是完全有效的。
If you want a two dimensional array with compile-time known size, just use a two dimensional array! float val[5][3]
is perfectly valid.
如果你想有一个二维数组,你不知道这是在编译时的大小,你最有可能要使用标准的单一diemensional释放calloc()和适当的getter。
If you want a two dimensional array and you don't know it's size during compile-time, you most probably want to use a standard, single diemensional calloc() and an appropriate getter.
#define ARR_COLUMNS 10
#define ARR_ROWS 10
float* arr = calloc (ARR_COLUMNS * ARR_ROWS, sizeof(float));
int get(float* arr, int x, int y) {
if (x<0 || x>= ARR_COLUMNS) return 0;
if (y<0 || y>= ARR_ROWS) return 0;
return arr[ARR_COLUMNS*y+x];
}
void set (int* arr, int x, int y, float val) {
if (x<0 || x>= ARR_COLUMNS) return;
if (y<0 || y>= ARR_ROWS) return;
arr[ARR_COLUMNS*y+x] = val;
}
当然,与相应的变量替换定义。
Of course replace the defines with appropriate variables.
这样做你会:
- 保存自己昂贵的allocs和释放
- 有比较完整的内存
- 简化您可能realloc的通话
- 确保数据被缓存更好,没有共同的[X]访问[Y] VS [Y] [X]迭代缓存出现了问题。
这篇关于正确的方法来分配和指针的免费阵列阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!