C将可变大小的2-D数组传递给函数 [英] C pass variable size 2-D array to function
问题描述
我正在尝试重构代码以使其更佳/更具可读性,因此我尝试如下更改二维变量数组分配
I'm trying to refactor my code to make it better/more readable so I'm trying change a 2-D variable array allocation as follows
// OLD CODE
int **map;
map = calloc(number, sizeof(int *));
if (!(map)) {
free(map);
return 1;
}
for (int i = 0; i < number; i++) {
map[i] = calloc(number, sizeof(int));
if (!(map[i])) {
while (--i >= 0) {
free(map[i]);
}
free(map);
return 1;
}
}
// NEW CODE
int (*map)[number] = malloc(sizeof (int[number][number]));
if (!(map)){
free(map);
return 1;
}
问题是我所有使用map的函数都使用了int **map
,并且像我IDE告诉我的那样通过更改map的声明incorrect type int[]* instead of int**
我应该使用什么代替int**
?在函数声明中使用int[]* map
会告诉我can't resolve variable map
The problem is that all my functions that use map take int **map
and by changing the declaration of map like i did the IDE tells me incorrect type int[]* instead of int**
What should i use instead of int**
? Using int[]* map
in the function declaration tells me can't resolve variable map
推荐答案
要使用带有标准代码的一种分配,不同于其他答案有点棘手,因为需要确保在int
对齐要求的异常情况下,指针和int
的组合内存分配需要满足对齐问题,而不是指针对齐.使用long long
可以更容易地显示出来,如下所示.
To use one allocation with standard code, unlike the other answer, is a bit trickier as one needs to insure that a combined memory allocation of pointers and int
needs to meet alignment concerns in the unusual case of int
alignment requirements exceed pointer alignment ones. This is more easily shown with long long
as below.
如果这使代码更易于阅读",则由OP判断.
If this makes "code easier to read" is left to OP's judgment.
#include <stdlib.h>
#include <stdio.h>
long long **map_allocate_ll(size_t row, size_t column) {
long long **map;
long long *ints;
size_t pointers_sz = sizeof *map * row;
// extend pointer size to `*ints` boundary
pointers_sz = (pointers_sz + sizeof *ints - 1)/sizeof *ints * sizeof *ints;
size_t ints_sz = sizeof *ints * row * column;
printf("psize %zu, isize %zu\n", pointers_sz, ints_sz);
map = calloc(1, pointers_sz + ints_sz);
if (map == NULL) {
return NULL;
}
ints = (void*) ((char*) map + pointers_sz);
printf("map %p\n", (void *) map);
for (size_t i = 0; i<row; i++) {
map[i] = &ints[i * column];
printf("map[%zu] %p\n", i, (void *) map[i]);
}
return map;
}
int main() {
free(map_allocate_ll(5,3));
}
样本输出
psize 24, isize 120
map 0x80081868
map[0] 0x80081880
map[1] 0x80081898
map[2] 0x800818b0
map[3] 0x800818c8
map[4] 0x800818e0
这篇关于C将可变大小的2-D数组传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!