defining a 2D array with malloc and modifying it

前端 未结 7 1193
陌清茗
陌清茗 2020-12-01 13:43

How do i define a 2D array using malloc ? (lets say 10X20).

second, can i increase number of rows or cols without creating a new increased array and copying all data

7条回答
  •  余生分开走
    2020-12-01 13:59

    A 2D array is an 1D array of 1D arrays. As an array is simply a pointer, an array of arrays is an array of pointers. So, you use malloc to allocate an array of pointers (each representing a collumn), then use it again to allocate the individual arrays (each representing a row).

    To expand/shrink the array, you use realloc(reference). Here's an example code:

    #include 
    #include 
    
    int** alloc_matrix(int w, int h) {
        int** matrix;
    
        matrix = (int**) malloc(sizeof(int*) * h);
        for(int i = 0; i < h; i++) {
            matrix[i] = (int*) malloc(sizeof(int) * w);
        }
    
        return matrix;
    }
    
    void realloc_matrix(int*** matrix, int new_w, int new_h) {
        *matrix = (int**) realloc((void *)*matrix, sizeof(int*) * new_h);
    
        for(int i = 0; i < new_h; i++) {
            (*matrix)[i] = (int*) realloc((void *)(*matrix)[i], sizeof(int) * new_w);
        }
    }
    
    int main(int argc, char* argv[]) {
        // Allocating matrix
        int** m = alloc_matrix(10, 15);
    
        // Filling with some data
        for(int y = 0; y < 15; y++) {
            for(int x = 0; x < 10; x++) {
                m[y][x] = y * x; // Notice the index is [y][x] - NOT [x][y]!
            }
        }
    
        // Printing
        for(int y = 0; y < 15; y++) {
            for(int x = 0; x < 10; x++) {
                printf("%d\t", m[y][x]); // Notice the index is [y][x] - NOT [x][y]!
            }
            printf("\n");
        }
    
        // Reallocating
        realloc_matrix(&m, 20, 10);
    
        // Filling with some data
        for(int y = 0; y < 10; y++) {
            for(int x = 0; x < 20; x++) {
                m[y][x] = y * x; // Notice the index is [y][x] - NOT [x][y]!
            }
        }
    
        // Printing
        for(int y = 0; y < 10; y++) {
            for(int x = 0; x < 20; x++) {
                printf("%d\t", m[y][x]); // Notice the index is [y][x] - NOT [x][y]!
            }
            printf("\n");
        }
    }
    

    I'm sorry if I've got anything wrong. My C-fu is kinda rusty :)

提交回复
热议问题