Help with Arithmetic Pointer

I am learning C ++ for a test, and I'm currently stuck with pointer arithmetic.

The main problem is as follows:

int numColumns = 3;
int numRows    = 4;

int a[numRows][numColumns];

a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;
a[2][0] = 7;
a[2][1] = 8;
a[2][2] = 9;
a[3][0] = 10;
a[3][1] = 11;
a[3][2] = 12;

for (int i=numColumns-1; i>-1;i--)
{
  cout << a[numRows-1][i] << endl;
}

A very simple program that prints the bottom "row of matrix". those. 12.11.10.

Now I'm trying to make an equivalent with int *.

What my classmates told me is to think like this:

array[i][j] == p[numColumns*i+j]

If this is correct, the following should not be equivalent to what I am looking for:

int* p = reinterpret_cast<int*> a;
for (int i=numColumns-1; i>-1;i--)
{
  cout << p[numColumns*(numRows-1)+i] << endl;
}

Thank.

+3
source share
4 answers

int array[3][5] ( ++) int array[3*5]. , 2- ( N- ) . array[3][5] , , 5 ( ). ++ .

++ T array[N] , N T. , , , , int array [3] [5], , 3 int[5] , int[5] 5 ints.

, - int array[3*5]. , , - ( int[] int[][]). reinterpret_cast, " , ".

, . , , . ( , ), , int[5] 5 ( char[5], , 8 ).

int* int**, .

EDIT: , ++ int[3*5] int[3][5], , . ++ int[0][1] int[0][2] sizeof(int). Fortran, , int[0][0] int[1][0] sizeof(int) , Fortran .

, :

0 1 2
3 4 5
6 7 8

, {0,1,2,3,4,5,6,7,8} , : {0,3,6,1,4,7, 2,5,8}.

+2

: a int**, int*. .

, 1-D , a 1-D .

+1

@rwong: ? , "", :

int array[3][5];
int array[3*5];

, , . , , .

:

for(int i=numRows-1; i>-1 ;i++)
{
  cout << p[numColumns*numRows-1+i] << endl;
}

, VS, , "" .

, ;)

: , rwong. - ?

0

: a int**, a, int*?

0

Source: https://habr.com/ru/post/1761794/


All Articles