我有一个庞大的代码,但是为了测试,我创建了下面的示例代码
#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 : %d\n", 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 @ %d\n", i);
} else {
printf ("mem allocated @ %d\n", i);
}
}
}
return 0;
}我想让*mymap10 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 : %d\n", 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 : %d\n", cnt);
}
}有什么办法可以避免吗?能帮我吗?
发布于 2021-09-18 10:51:46
使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();
...
}如果需要,可以在前面的示例中将malloc()替换为posix_memalign()。例如:
// 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;https://stackoverflow.com/questions/69233201
复制相似问题