Correct way to allocate and free arrays of pointers to arrays

前端 未结 3 1266
自闭症患者
自闭症患者 2021-01-02 02:46

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 allocate         


        
3条回答
  •  春和景丽
    2021-01-02 03:37

    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.

    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.

    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.

    By doing so you will:

    • save yourself costly allocs and frees
    • have less fragmented memory
    • simplify your possible realloc calls
    • ensure the data is cached better and accessed without the common [x][y] vs [y][x] iteration cache problem.

提交回复
热议问题