Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
213 views
Welcome To Ask or Share your Answers For Others

1 Answer

Turns out the below code is not a C99 alternative @M.M, but a GCC extension.

Undocumented GCC Extension: VLA in struct


As a C99 GCC extension alternative to int (*map)[number] = malloc(sizeof (int[number][number])); for code simplification and maintain compatibility with existing function set, allocate all the memory needed with 1 *alloc() call.

This does require that when code is done with the map, all the memory is free'd with one free(map). Further, individual rows of map[] can no longer be re-allocated, but can be swapped within the map[].

int **map_allocate(size_t row, size_t column) {
  struct {
    int *ip[row];        // Array of pointers, followed by a ...
    int i[row][column];  // 2D array of int
  } *u;
  u = calloc(1, sizeof *u);
  if (u == NULL) {
    return NULL;
  }
  for (size_t i = 0; i<row; i++) {
    u->ip[i] = u->i[row];
  }
  return &u->ip[0];
}

Note: no casting and field i[][] is properly aligned.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...