Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef with arrays in C

Tags:

c

typedef

Hello I am new to C programming. After using python for a long time, C seems infinitely harder (and well infinitely more fun)!

What I cannot wrap my head around is using typedef with arrays and in particular 2D Arrays.

typedef double vector_t[10];

As far as I understand this helps us use vector_t to initialise an array of doubles with 10 elements. So would initialising vector_t[10] initialise an Array of [10][10]?

Also what if I initialise vector_t[5]?

typedef vector_t second_t[5];

What will happen if I use second_t? Will the 2d array be array of [10][5] or an array of [5][10]?

like image 967
John Smith Avatar asked Oct 07 '17 23:10

John Smith


1 Answers

If you use

second_t v;

That's exactly the same as

vector_t v[5];

And that's exactly the same as

double v[5][10]; /* NOT double[10][5] */

When you expand a typedef, imagine that you're substituting whatever's after the typedef for the typedef's name in its definition:

typedef something t[size];
t x;
/* subst [t := x] into the typedef definition */
something x[size];

second_t v;
/* [second_t := v] in definition */
vector_t v[5];
/* [vector_t := v[5]] in definition */
double v[5][10];

typedef int (*unary_op)(int); /* pointers to functions int => int */
typedef int (*consumer)(unary_op); /* pointers to functions (int => int) => int */
consumer f;
/* [consumer := f] in definition */
int (*f)(unary_op);
/* [unary_op := ] (replace unary_op with "", because there's no name) in definition.
   We must respect parentheses */
int (*f)(int (*)(int));
// Something like int func(unary_op op) { return op(5); }
like image 142
HTNW Avatar answered Oct 09 '22 22:10

HTNW