简体   繁体   中英

Dynamic array of fixed size array

How do you allocate an array comprised of fixed size array of floats ? I tried this:

float **sub_uvs = malloc(sizeof(float [2]) * size * size);
/* Seg. fault */
sub_uvs[0][0] = 0.3;
sub_uvs[0][1] = 0.4;

You will have to perform another, separate allocation for the second array, presumably using another call to MEM_allocN . You will also have to free this memory separately, using whatever deallocation function the platform provides.

The memory representation will be completely different, so even if it is syntactically more convenient in some places, it could be difficult to make this work everywhere.

Multidimensional arrays of variable size are still tricky. Several options:

  1. Use an array of pointers to arrays. Use one malloc for the array of pointers, then loop over malloc to make each row-array. But, this is a whole different data structure.

  2. Find a class providing memory management and multidimensional indexing methods. Perhaps Blender has one?

  3. Use Eigen or a similar complete math library.

or you can use following :)

float **a;
a = (float **)malloc(sizeof(float *) * size_row);

for(int i=0;i<size_row;i++)
{
    a[i] = (float *)malloc(sizeof(float) * size_col);
}
a[0][0] = 0.4;

printf("%f",a[0][0]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM