typedef and array
- C course
- Intermediate
- Lesson 108/116
- 5 min
Learn to define array types with typedef.
typedef and array
typedef also names array types. Multi-dimensional arrays have complex syntax; typedef simplifies the code.
Example: typedef int Matrix[3][3];. This names a 3×3 integer matrix type Matrix. From then on you write Matrix m; instead of int m[3][3];. Each element is accessed as m[i][j]. This pattern is common in mathematical calculations and game board representation. The type name reflects the purpose; when someone writes Matrix, everyone expects a 3×3 integer matrix.
Matrix initialization
You initialize a Matrix variable with nested brace lists. Each inner list represents a row.
Example: Matrix m = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };. This lays out the numbers 1 through 9 in a 3×3 grid. m[0][0] = 1, m[1][1] = 5, m[2][2] = 9. Inner braces separate rows; they improve readability. This structure is the basis of matrix operations and tabular data. Thanks to typedef, it is declared concisely and meaningfully as Matrix.
Practice Write a Matrix program
Define typedef int Matrix[3][3];. In main create Matrix m = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };. Print the center element with printf("%d\n", m[1][1]);.
Starter code
#include <stdio.h>
// Define the Matrix type with typedef
// Initialize m with values
// Print m[1][1]
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
typedef int Matrix[3][3];
int main(void) {
Matrix m = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
printf("%d\n", m[1][1]);
return 0;
}Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the matrix access
printf("%d
", m[1][____]);
printf("%d
", m[1][1]);
Explanation: m[1][1] is the center element of the matrix.
2 Match the matrix indices
| Term | Meaning |
|---|---|
m[0][0] |
Top left |
m[1][1] |
Center |
m[2][2] |
Bottom right |
Matrix |
Type name |
3 What does typedef int Matrix[3][3]; define?
- A 3-element array
- A 3×3 integer matrix type Correct answer
- A pointer type
- A function type
Explanation: Matrix is a 3×3 integer two-dimensional array type.