Correct way to allocate and free arrays of pointers to arrays

前端 未结 3 1250
自闭症患者
自闭症患者 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:33

    I want to create an array of pointers to arrays of 3 floats. What is the correct way to do this?

    Why do you want an array of pointers to arrays? Wouldn't an array of arrays be sufficient? (Keep in mind that arrays are already pointer-like, they are not passed by value, rather the address of the first element is passed when an array is passed as an argument to a function).

    // stack allocation, no need to free
    float array[SIZE][3]; 
    
    for (int i = 0; i < SIZE; i++) {
        // do something with array[i][0], array[i][1], array[i][2]
    }
    

    Then how would I free the data?

    In this case you wouldn't, since the data is stack allocated (will be cleaned up automatically once out of scope). Just remember the rule of thumb is that for every memory allocation you make, a corresponding free is necessary. So if you allocate memory for an array of floats, as in

    float* arr = malloc(sizeof(float) * 3); // array of 3 floats
    

    Then you only need to call free on the array that you malloc'd, no need to free the individual floats. If you perform nested allocation as in

    // array of length SIZE, consisting of float pointers
    float** arr = malloc(sizeof(float*) * SIZE);
    
    // allocate the array of 3 floats at each index
    for (int i = 0; i < SIZE; i++) 
        arr[i] = malloc(sizeof(float) * 3);
    

    Then you will need to perform a free for every malloc, as in

    // free the individual arrays
    for (int i = 0; i < SIZE; i++)
        free(arr[i]);
    // free the array of arrays
    free(arr);
    

    The lesson to take away here is to avoid dynamic allocation of arrays all-together. Stick with either std::vector or stack-allocated arrays.

提交回复
热议问题