0

I am new to c language, and I have been trying to find an efficient and flexible way to define 2D matrices in c language. My goal is to create 2D matrices freely from anyplace in my program and being able to pass any number of matrices back to the main code. Below is my code and a figure that explains my understanding of this code. I tried my best to avoid ***pointers but I couldn't, please correct me if you think there is a better way to achieve this goal.

Matrix definition using a ***pointer.

#include<stdio.h>
#include<stdlib.h>

void createMatrix(int ***Mat, int N){
    // Create N rows pointers
    (*Mat) = malloc(N*sizeof(int *));
    // For each row point, create N columns 
    for(int i=0; i<N; i++){
        (*Mat)[i] = malloc(N*sizeof(int));
    }
    // Initialize matrix elements
    for(int i=0; i<N; i++){
        for(int j=0; j<N; j++){
            (*Mat)[i][j] = 0;
        }
    }
};

void printMatrix(int ***Mat, int N){
    // Print matrix elements
    for(int i=0; i<N; i++){
        for(int j=0; j<N; j++){
            printf("%d ", (*Mat)[i][j]);
        }
        printf("\n");
    }
};

void main(){
    
    int N = 10;
    
    // Allocate the pointers
    int ***A;
    A = malloc(sizeof(int *));
    
    // Call the functions
    createMatrix(A, N);
    printMatrix(A, N);
    free(A);
}
M. Mustafa
  • 21
  • 6
  • 2
    See [**Correctly allocating multi-dimensional arrays**](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays) – Andrew Henle Dec 14 '20 at 14:04
  • I saw the answer in the link. Yes, it was useful but it didn't answer my question. Try the code in that link for a matrix size 5000 x 5000, and the program stops running! If you try my code the program doesn't crash. Think of it, the contiguous allocation of 2D array limits the maximum size of the array. On the other hand, the fragmented allocation with a LUT helps efficiently utilize the memory and allows bigger matrices. – M. Mustafa Dec 14 '20 at 14:55
  • Allocation of 100 MB is the same whether done a piece at a time or all at once. It is only contiguous in virtual addresses, not in physical memory. – stark Dec 14 '20 at 15:02
  • Then how do you explain my observation? Defining 5000 X 5000 contiguous elements doesn't work, but defining 5000 x 5000 elements on arbitrary locations using malloc twice works? – M. Mustafa Dec 14 '20 at 15:16
  • Your matrix is too big to be allocated in the "stack" using a VLA, but there shouldn't be any problem with a contiguous allocation in the free space: https://godbolt.org/z/75Y4G3 – Bob__ Dec 14 '20 at 15:46
  • Some more sophisticated algorithms [might](https://stackoverflow.com/questions/38190006/matrix-multiplication-why-non-blocked-outperforms-blocked) store the elements as a [block matrix](https://en.wikipedia.org/wiki/Block_matrix) to be more cache friendly. – Bob__ Dec 14 '20 at 15:54
  • Thanks Bob__, this is interesting. – M. Mustafa Dec 14 '20 at 16:14

0 Answers0