Home > Software engineering >  Printing the value of 2d array stored in another function
Printing the value of 2d array stored in another function

Time:11-04

i currently have a array function that reads in values of user input and I want to print out the array using another function.

this is my code

Function to read in user input and store in 2d array

void readMatrix(){

    int arr[3][4];
    int *ptr;

    for (int i = 0; i < 3; i  )
    {
        for (int j = 0; j < 4; j  )
        {
            printf("row %d, col %d: ", i   1, j   1);
            scanf("%d", &arr[i][j]);
        }

    ptr = &arr;
    
    }
    
}

function to print array stored in readMatrix() function

void printMatrix(){

    for (int i = 0; i < 3;   i)
    {
        for (int j = 0; j < 4;   j)
        {
        printf("row %d, col %d = %d\n", i   1, j   1, arr[i][j]);
        }
    }
    
}

int main(){

    //function to read matrix
    readMatrix();
  
    //function to print matrix
    printMatrix();
    return 0;
}

CodePudding user response:

int arr[3][4]; is a local variable only valid inside that function, so you can't pass it to anyone else. The easiest and best solution is to use caller allocation instead. You can also rewrite the functions to work with variable amounts of rows/cols.

With just a few tweaks to your code:

#include <stdio.h>

void readMatrix (int rows, int cols, int arr[rows][cols]){
    for (int i = 0; i < rows; i  )
    {
        for (int j = 0; j < cols; j  )
        {
            printf("row %d, col %d: ", i   1, j   1);
            scanf("%d", &arr[i][j]);
        }
    }
}

void printMatrix (int rows, int cols, int arr[rows][cols]){
    for (int i = 0; i < rows;   i)
    {
        printf("{ ");
        for (int j = 0; j < cols;   j)
        {
            printf("%2.d ", arr[i][j]);
        }
        printf("}\n");
    }
}

int main (void)
{
    int arr[3][4];
    readMatrix(3,4,arr);
    printMatrix(3,4,arr);
    return 0;
}

Input:

1 2 3 4 5 6 7 8 9 10 11 12

Output:

{  1  2  3  4 }
{  5  6  7  8 }
{  9 10 11 12 }

If you don't understand why this works, then "array decay" is the next best thing to study. What is array to pointer decay?

  •  Tags:  
  • c
  • Related