Print values of a 2D Dynamic matrix

Viewed 35

i cannot find solution how to solve this.

rows number is easy one. reading from keyboard and allocation but column number is different for each row. lets assume user entered 2 rows after that user entered 3 column for row 0 and 10 column for row 1 and i dont know how to enter values for these columns and print them. because every column has different length. unfortunately != NULL not working

int** ptr; int rows, columns;
printf("enter number of rows..\n");
scanf("%d", &rows);

ptr = (int**)calloc(rows, sizeof(int*));

for (size_t i = 0; i < rows; i++) // allocation an array of integers for every row
{
    printf("enter number of columns..\n");
    scanf("%d", &columns);
    ptr[i] = (int*)calloc(columns, sizeof(int));
}
for (size_t i = 0; i < rows; i++){
    for (size_t j = 0; ptr[i][j] != NULL; j++)
        ptr[i][j] = j;
}
for (size_t i = 0; i < rows; i++){
    for (size_t j = 0; ptr[i][j] != NULL; j++)
    printf("%d\n", ptr[i][j]);  
}
1 Answers

Since C arrays don't have a final delimiter, then you need to store the length in an efficient way:

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

int main()
{
    int** ptr; int rows, columns;
    printf("enter number of rows..\n");
    scanf("%d", &rows);
    
    ptr = (int**)calloc(rows, sizeof(int*));
    
    for (size_t i = 0; i < rows; i++) // allocation an array of integers for every row
    {
        printf("enter number of columns..\n");
        scanf("%d", &columns);
        ptr[i] = (int*)calloc(columns+1, sizeof(int)); // Last pos will save the size
        
        // We need to track the columns since C arrays do not have a final delimiter
        ptr[i][columns] = INT_MIN; // It could also be INT_MAX depending on our needs
    }
    
    for (size_t i = 0; i < rows; i++){
        for (size_t j = 0; ptr[i][j] != INT_MIN; j++)
            ptr[i][j] = j;
    }
    
    for (size_t i = 0; i < rows; i++)
    {
        printf("Line %li\n", i);
        for (size_t j = 0; ptr[i][j] != INT_MIN; j++)
        {
             printf(" Column %li: ", j);
             printf("%d\n", ptr[i][j]);
        }
    }

    return 0;
}
Related