#include<iostream>
    #include <iomanip>
    //#include<fstream>
    using namespace std;
    int main()
    {
    int input = 1;
    int matrix[3][4];
    int trans [4][3];
    for(int i=0; i<3; i++) //This loops on the rows.
    {
    for(int j=0; j<4; j++) //This loops on the columns
    {
    matrix[i][j] = input;
    input++;
    }
    }
    for(int i=0; i<3; i++) //This loops on the rows.
    {
    for(int j=0; j<4; j++) //This loops on the columns
    {
    cout << setw(2) << matrix[i][j] << " "; // setw(2) for alignment
    }
    cout << endl;
    }

    cout << endl;

    for(int i=0; i<4; i++) //This loops on the rows.
    {
    for(int j=0; j<3; j++) //This loops on the columns
    {   
    trans [i][j] = matrix [j][i];
    cout << trans [i][j] << " ";
    }
    cout <<   endl;
    }
    return 0;
    }

want to define a pointer that you can use to access the
Arrays made above. and then be able to print out elements x(1,3) and y(2,1) , these being examples. any ideas how to do so?

Dani AI

Generated

Brief answer tied to 's arrays: there are two simple, safe ways to use pointers to access your matrix[3][4] and trans[4][3]. Remember C/C++ arrays are zero-based, so if you want to refer to x(1,3) as a 1-based pair you must subtract 1 from each index.

Pointer-to-row (clean, type-safe):

int (*pmatrix)[4] = matrix;   // pmatrix points to rows of 4 ints
int (*ptrans)[3]  = trans;    // ptrans points to rows of 3 ints

int x_1_3 = pmatrix[1-1][3-1]; // x(1,3) using 1-based => pmatrix[0][2]
int y_2_1 = ptrans[2-1][1-1];  // y(2,1) => ptrans[1][0]
cout << x_1_3 << ' ' << y_2_1 << '\n';

Flattened pointer (works when you need linear arithmetic):

int *flat = &matrix[0][0];     // row-major layout
int x = flat[(1-1)*4 + (3-1)]; // row*NUM_COLS + col

Notes and cautions: statically declared 2D arrays are stored row-major, so the flat-index formula is row*COLS + col. Do not use int** to point at a true 2D array — that has different semantics and will lead to bugs. For authoritative reference on array layout and types see cppreference on arrays: . As hinted, try these approaches and post any failing output if you hit a wall.

Recommended Answers

All 3 Replies

?

Sure, but what do YOU think is the right approach?

FWIW, we don't solve your class problems for you, but will help once you make an honest effort to do so yourself and have hit some wall.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.