Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do 2d arrays work in C when using typedef?

Lecture Slide question that I need help on: Lecture Slide question that I need help on:

I missed my lecture today, so I have no idea what is going on for this question in the lecture slides. My instinct tells me it would be C. and N x M matrix (row x col), but I'm not too sure. Any help is appreciated

like image 542
Satan Lucifer Avatar asked Jan 20 '26 22:01

Satan Lucifer


2 Answers

double X_t[N] denotes the type of an array with N elements of the type double.

X_t A[M]; is a declaration of an array with M elements that have the type double[N].

So this declaration is equivalent to

double A[M][N];

Here is a demonstrative program.

#include <stdio.h>

int main(void) 
{
    enum { M = 2, N = 5 };
    typedef double X_t[N];
    
    printf( "sizeof( X_t ) = %zu\n", sizeof( X_t ) );
    
    putchar( '\n' );
    
    X_t A[M];
    
    printf( "sizeof( A ) = %zu\n", sizeof( A ) );
    printf( "sizeof( A[0] ) = %zu\n", sizeof( A[0] ) );
    printf( "sizeof( A ) / sizeof( A[0] ) = %zu\n", sizeof( A ) / sizeof( A[0] ) );
    

    return 0;
}

The program output is

sizeof( X_t ) = 40

sizeof( A ) = 80
sizeof( A[0] ) = 40
sizeof( A ) / sizeof( A[0] ) = 2

So it is seen that the array A has two elements with the size 40 bytes that is equivalent to N * sizeof( double ).

like image 139
Vlad from Moscow Avatar answered Jan 23 '26 13:01

Vlad from Moscow


It's b, and MxN array of doubles.

typedef double X_t[N];

defines X_t as an array of N doubles.

When you make an array of these, each X_t is a row. So

X_t A[M];

creates M rows of this.

like image 30
Barmar Avatar answered Jan 23 '26 11:01

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!