Passing a 2d array to a function, using the pointer to a 2D array

Discussion in 'C' started by Dragu Mircea, Jun 11, 2021.

  1. Dragu Mircea

    Dragu Mircea New Member

    Joined:
    Apr 15, 2018
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Hi,

    I am trying to make a program, a read from the keyboard a 2d array and print his elements.
    It works, but i am not so sure is very good, because when i compile, take a while and it finish with a delay.
    When I make debug I obtain a segmentation fault. So, I need some help.
    Thank you in advance.

    #include <stdio.h>​

    #define ARRAY_ROW 3
    #define ARRAY_COL 3​

    void WriteArray3(int(*piData)[ARRAY_ROW][ARRAY_COL])
    {
    int iRow = 0;
    int iCol = 0;​

    for(iRow = 0; iRow<ARRAY_ROW; iRow++)
    {
    for(iCol = 0; iCol<ARRAY_COL; iCol++)
    {
    printf("\n Element[%d][%d] = ", iRow, iCol);
    scanf("%d", &piData[iRow][iCol]);
    }
    printf("\n");
    }​
    }​

    void ReadArray3(int(*piData)[ARRAY_ROW][ARRAY_COL])
    {
    int iRow = 0;
    int iCol = 0;​

    printf("\n");
    for(iRow = 0; iRow<ARRAY_ROW; iRow++)
    {
    for(iCol = 0; iCol<ARRAY_COL; iCol++)
    {
    printf(" %d ", (*piData[iRow][iCol]));
    }
    printf("\n\n");
    }​
    }​

    int main()
    {
    int aiData[ARRAY_ROW][ARRAY_COL];​

    WriteArray3(&aiData);
    ReadArray3(&aiData);​

    return 0;​
    }
     
  2. rustyoldguy

    rustyoldguy New Member

    Joined:
    Feb 21, 2020
    Messages:
    3
    Likes Received:
    2
    Trophy Points:
    3
    Gender:
    Male
    Location:
    Germany
    Hallo Dragu!

    Here is my suggestion:

    Code:
    #include <stdio.h>
    #define ARRAY_ROW 3
    #define ARRAY_COL 3
    
    
    void WriteArray3(int(*piData)[ARRAY_ROW][ARRAY_COL])
    {
    int iRow = 0, iCol = 0;
    
    for(iRow = 0; iRow<ARRAY_ROW; iRow++)
    {
    for(iCol = 0; iCol<ARRAY_COL; iCol++)
    {
    printf("\n Element[%d][%d] = ", iRow, iCol);
    scanf("%d", &(*piData)[iRow][iCol]);
    }
    printf("\n");
    }
    }
    
    void ReadArray3(int piData[ARRAY_ROW][ARRAY_COL])
    {
    int iRow = 0, iCol = 0;
    
    printf("\nShow Values of array[%d][%d]\n", ARRAY_ROW, ARRAY_COL);
    
    for(iRow = 0; iRow<ARRAY_ROW; iRow++)
    {
    for(iCol = 0; iCol<ARRAY_COL; iCol++)
    {
    printf(" %d ", piData[iRow][iCol]);
    }
    printf("\n");
    }
    
    printf("-----------------------\n");
    }
    
    int main()
    {
    int aiData[ARRAY_ROW][ARRAY_COL] = {0};
    printf("Get values\n");
    WriteArray3(&aiData);
    ReadArray3(aiData);
    
    return 0;
    }
    
     
    Last edited: Jun 19, 2021

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice