Correct way to allocate and free arrays of pointers to arrays

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

    If you know the array size at compile time (and you do, if SIZE is a compile-time constant), you should just declare a two-dimensional array. You don't need to free this at all (and must not).

    float array1[SIZE][3];
    

    You need to use calloc, and to create an array of pointers, only if the dimensions are not known at compile time. In this case, there should be one call to free for each call to calloc. And since you cannot use an array after you free it, you need to free the row arrays before you free array1.

    float **array1 = calloc(nrows, sizeof (float *));
    for (int i=0; i < nrows; i++)
        array1[i] = calloc(3, sizeof(float));
    // Use it...
    
    // Now free it
    for (int i=0; i < nrows; i++)
        free(array1[i]);
    free(array1);
    

    Edit: if you won't be rearranging the pointers (to sort the rows in-place, for example), you can do all of this with just one calloc (and one call to free afterwards):

    float (*array1)[3] = calloc(3*nrows, sizeof (float));
    

    That's because the number of columns is known at compile-time, and that's all the pointer arithmetic needs to know. Then you can write things like array1[i][j], and you can still pass around array1[i] as if it was a real pointer to a row. C is great that way, take advantage of it!

提交回复
热议问题