我有一个巨大的代码,但为了测试,我创建了以下示例代码
#include <stdio.h>
#include <stdlib.h>
#define POSSIBLE_HEIGHTS 10
#define POSSIBLE_LENGTHS 10
typedef struct amap {
int *va_height;
int *va_length;
} amap_t;
static amap_t *mymap[10];
int prepare_mymap(amap_t **);
int main (int argc, char *argv[]) {
prepare_mymap(&mymap[0]);
short int cnt;
int max = 10;
for (cnt = 0; cnt < max; ++cnt){
if (mymap[cnt] != NULL){
if (mymap[cnt]->va_height == NULL){
printf ("Heights are not set for : %dn", cnt);
}
}
}
return 0;
}
int prepare_mymap (amap_t **arg_map){
short int i;
for (i =0; i < 10; ++i){
if (i % 2 == 0) {
int r = posix_memalign ((void **) &arg_map[i], 16,
(sizeof(int) * POSSIBLE_HEIGHTS));
if (r != 0) {
printf ("memalign failed @ %dn", i);
} else {
printf ("mem allocated @ %dn", i);
}
}
}
return 0;
}
我想让*mymap[10]是动态的。函数prepare_mymapp()
将决定mymap中元素的数量;其中有些被分配,有些没有。我的问题是不改变访问方法主要是有可能使static amap_t *mymap[10];
动态?
我不想改变main(),因为它是一个巨大的代码,使用指针和检查NULL。
if (mymap[cnt] != NULL){
if (mymap[cnt]->va_height == NULL){
printf ("Heights are not set for : %dn", cnt);
}
}
如果我这样做:
static amap_t *mymap;
prepare_mymap(&mymap);
and
int prepare_mymap (amap_t **arg_map){
int arg_map_size = 10;
*arg_map = malloc (sizeof(amap_t *) * arg_map_size);
....
posix_memalign.....
}
然后我的主修改成这个
if (*mymap[cnt] != NULL){
if (mymap[cnt].va_height == NULL){
printf ("Heights are not set for : %dn", cnt);
}
}
有办法避免吗?***能帮我吗?
使static amap_t* mymap[10]
成为动态数组的一种方法是这样声明:
static amap_t** mymap;
相应地,您的prepare_mymap()
函数变为:
static amap_t** mymap;
int prepare_mymap(amap_t*** arg_map) {
size_t arg_map_size = 10;
*arg_map = malloc(arg_map_size * sizeof(amap_t*));
...
}
int main(void) {
prepare_mymap(&mymap);
...
}
或者,你的prepare_mymap()
函数可以直接返回指针(所以你不需要"三星")指针作为参数):
static amap_t** mymap;
amap_t** prepare_mymap(void) {
size_t arg_map_size = 10;
amap_t** result = malloc(arg_map_size * sizeof(amap_t*));
...
return result;
}
int main(void) {
mymap = prepare_mymap();
...
}
如果你愿意,你可以用posix_memalign()
代替我前面的例子中的malloc()
。例如:
// this line of code
*arg_map = malloc(arg_map_size * sizeof(amap_t*));
// becomes
void* temp;
int r = posix_memalign(&temp, alignment, arg_map_size * sizeof(amap_t*));
*arg_map = temp;