简体   繁体   中英

C 2 dimensional array with variable size rows

is there any convenient way to create a matrix without using malloc? This kind of works:

int *arr2d[3];
int arr0[] = { 0 };
int arr1[] = { 0, 1 };
int arr2[] = { 0, 1, 2 };

arr2d[0] = arr0;
arr2d[1] = arr1;
arr2d[2] = arr2;

printf(%d, arr2d[i][j]);

It doesn't allow you to loop through the values easily as you can't get the size of each subarray as you could using sizeof for arr2d[3][3].

sizeof arr2d[i] / sizeof arr2d[i][0]

Is there any better way to do this?

For reference, here is the same kind of question for C++:

C++ 2 dimensional array with variable size rows

You cannot do that: in this case, sizeof is evaluated statically, and it represents the size of the pointer. If you need to implement a jagged array with different sizes per row, you have two options:

  • When the size can be computed from the row index, eg in a "triangular" array like yours (array length is row+1 ) you do not store anything at all
  • When the size is arbitrary, create a separate array size_t len[rows] , and store each length individually.

Using a struct and compound literals can be done on the stack only.

typedef struct
{
    size_t size ;
    int* a ;

} jag_array ;

jag_array m[] = { { 3 , ( int[] ){ 1,2,3 } } , 
                    6 , ( int[] ){ 1,2,3,4,5,6 } ,  
                    4 ,( int[] ){ 1,2,3,4 } } ;

This has limitations. When you copy the struct the arrays themselves are not copied.

Separate functions and macros could help handling this, but it is not that pretty.

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