Comprehensive Summary of Techniques for Using Two-Dimensional and Multi-Dimensional Arrays

“From today on, study hard and make progress every day”

Repetition is the best method for memory; spend one minute each day to remember the basics of C language.

C Language Beginner’s Essential Knowledge Points Note Series 100 Articles

The following notes finally enter the practical series, which is also the most important and difficult part of C language. Keep it up! Youngsters!

33. Comprehensive Summary of Techniques for Using Two-Dimensional and Multi-Dimensional Arrays, Hurry Up and Collect!

1. Basic Concept of Two-Dimensional Arrays

A two-dimensional array is an “array of arrays” and can be viewed as a table composed of rows and columns:

data_type array_name[rows][columns];

Memory Layout Characteristics

  • • Stored in row-major order
  • • Total size = number of rows × number of columns × sizeof(element type)
  • • Each element is accessed using two subscripts:<span>arr[row][col]</span>

2. Various Ways to Declare and Initialize Two-Dimensional Arrays

1. Basic Declaration

int matrix[3][4];  // A 3-row 4-column integer array, similar to a mathematical matrix

2. Complete Initialization

int arr[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};

3. Partial Initialization

int arr[3][4] = {
    {1},          // First row: 1,0,0,0
    {0, 2},       // Second row: 0,2,0,0
    {0, 0, 3}     // Third row: 0,0,3,0
};

4. Omitted Row Count Initialization

int arr[][3] = {  // Row count is automatically inferred as 2
    {1,2,3},
    {4,5,6}
};

3. Accessing and Traversing Two-Dimensional Arrays

1. Basic Access

int val = matrix[1][2];  // Get the element at row 2, column 3
matrix[0][1] = 10;       // Modify the element at row 1, column 2

2. Nested Loop Traversal

for (int i = 0; i < 3; i++) {         // Row loop
    for (int j = 0; j < 4; j++) {     // Column loop
        printf("%d ", matrix[i][j]);
    }
    printf("\n");
}

3. Memory Order Access Optimization

// It is recommended to access the elements of the two-dimensional array in row-major order for higher efficiency
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; j++) {
        process(matrix[i][j]);
    }
}

4. Memory Model of Two-Dimensional Arrays

1. Memory Arrangement Example

int arr[2][3] = {{1,2,3}, {4,5,6}};

Memory layout (contiguous storage):

1 2 3 4 5 6

2. How to Calculate Memory Addresses

printf("arr[0][0]: %p\n", &arr[0][0]);
printf("arr[0][1]: %p\n", &arr[0][1]);
printf("arr[1][0]: %p\n", &arr[1][0]);

5. Two-Dimensional Arrays and Pointers

1. Array Name Conversion

int arr[3][4];
int (*p)[4] = arr;  // Pointer to an array containing 4 ints

2. Pointer Access Method

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; j++) {
        printf("%d ", *(*(arr + i) + j));
    }
}

6. Concept of Multi-Dimensional Arrays

1. Three-Dimensional Array Example

int cube[2][3][4];  // 2 layers, 3 rows, 4 columns, can be considered a rectangular prism

2. Initialization and Access

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

printf("%d", cube[1][2][3]);  // 24

7. Arrays as Function Parameters

1. Passing Two-Dimensional Arrays

void printMatrix(int mat[][4], int rows) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < 4; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }
}

2. Must Specify Column Count

// Error! Must specify the size of the second dimension
void func(int mat[][]);  

// Correct
void func(int mat[][4]);

8. Implementation of Dynamic Two-Dimensional Arrays

1. Pointer Array Method

int **mat = malloc(rows * sizeof(int*));
for (int i = 0; i < rows; i++) {
    mat[i] = malloc(cols * sizeof(int));
}

2. Contiguous Memory Method

int *mat = malloc(rows * cols * sizeof(int));
// Accessing mat[i][j]: mat[i*cols + j]

9. Common Errors

1. Out-of-Bounds Access

int arr[2][3];
arr[2][0] = 5;  // Row out of bounds!

Correction:

if (row < 2 && col < 3) {
    arr[row][col] = value;
}

2. Mismatched Number of Initialized Elements

int arr[2][3] = {1,2,3,4,5,6,7};  // Error! Too many elements

Correction:

int arr[2][3] = {{1,2,3}, {4,5,6}};

Some students contacted me, wanting to have a study and communication group. Previously, I was worried about advertisements, so I didn’t create a group. Considering that having a group is indeed more convenient, I will try to create one this time.

If you need it, hurry up and join, valid for 7 days.

Comprehensive Summary of Techniques for Using Two-Dimensional and Multi-Dimensional Arrays

———- End ———-

[Special Statement: All articles in this public account are original or authorized by the author. Some content and images are sourced from the internet. Please feel free to consume them. The views are for learning reference only. If there are any errors, please forgive me.]

Comprehensive Summary of Techniques for Using Two-Dimensional and Multi-Dimensional Arrays

Comprehensive Summary of Techniques for Using Two-Dimensional and Multi-Dimensional Arrays

“If you like C, please like it”Comprehensive Summary of Techniques for Using Two-Dimensional and Multi-Dimensional Arrays Click the bottom right corner to viewComprehensive Summary of Techniques for Using Two-Dimensional and Multi-Dimensional Arrays

Leave a Comment