Ander Cash
Ander Cash

Reputation: 19

How to get size of Multi-Dmensional Array element in C?

How does this kind of array work? I'm only familiar with simple arrays but this one got me confused since it has multiple groups of 3 elements inside. How do I interpret the data to find the size using (sizeof(flashLayout)/sizeof(flashLayout[0]))? I'm learning C and any guidance is appreciated.

static const tFlashSector flashLayout[] =
{
 
   { 0x08000000, 0x00800,  0},          
   { 0x08000800, 0x00800,  1},          
   { 0x08001000, 0x00800,  2},           
   { 0x08001800, 0x00800,  3},          
   { 0x08002000, 0x00800,  4},       
   { 0x08002800, 0x00800,  5},          
   { 0x08003000, 0x00800,  6},                               
   { 0x08003800, 0x00800,  7},                                
   { 0x08004000, 0x00800,  8},                               
   { 0x08004800, 0x00800,  9},          
   { 0x08005000, 0x00800, 10},           
   { 0x08005800, 0x00800, 11},           
   { 0x08006000, 0x00800, 12},           
   { 0x08006800, 0x00800, 13},           
   { 0x08007000, 0x00800, 14},           
   { 0x08007800, 0x00800, 15},           
};

Upvotes: 1

Views: 57

Answers (2)

Gonen I
Gonen I

Reputation: 6107

Your example is a one dimensional array of elements of type tFlashSector. The inner {} brackets give initializers for each tFlashSector element.

Perhaps this simple example showing the same kind of initalization will make it more obvious:

struct point { int x; int y; };

int _tmain(int argc, _TCHAR* argv[])
{
    point points [] =
    {
        { 10, 10},          
        {20, 20},          
        {20, 10},          
    };
    printf("%d\n",(sizeof(points)/sizeof(points[0]))); // prints 3
    return 0;
}

Upvotes: 0

Bandi
Bandi

Reputation: 181

This is not a multi-dimensional array, but an array of initializer lists, so it has a single dimension, and you find it with the method you mentioned.

But to answer your question. In c you need to bound all the dimensions except the first. For example, this is how you store the indefinite amount of 3X3 matrixes.

const int arr[][3][3] = 
{
    {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 }
    },
    {
        { 10, 11, 12 },
        { 13, 14, 15 },
        { 16, 17, 18 }
    },
    {
        { 19, 20, 21 },
        { 22, 23, 24 },
        { 25, 26, 27 }
    }
};

You already need to know all the information except the last one, but you can calculate it with the same upper mentioned method.

Upvotes: 1

Related Questions