C ++ multidimensional arrays

First, by its very nature a multidimensional array is an array of arrays.

  int a [3] [4]; // array of size 3, which is an element of an array comprising four elements

  int a1 [3] [4] [5]; // array of size 3, which each element is an array of size 4, these are the elements of the array which contains an array of integers 5

  Interview questions:

       int a[4][5],(*p)[5];

       p = a;

       Which of the following represents a array of elements?

       A.  p+1

       B.  * (p+3)

       C.  * (p+1)+3

       D.  * (* p+2)

  Analysis: p is a pointer to a one-dimensional array, there are five types of elements int

    can be understood as a one-dimensional array, the elements of which a0, a1, a2, a3

    a1 is a one-dimensional array, in which elements a10, a11, a12, a13, a14

#include <the iostream> 
#include <stdio.h> 
the using namespace STD; 

int main () { 
	int A [. 4] [. 5], (P *) [. 5]; 
	P = A; 

	COUT P << << endl; // output 007FFC18 
	COUT. 1 + P << << endl; // output 007FFC2C, a difference of 20 is 
	COUT << endl << P + 2; // output 007FFC40, the same difference 20 is 
	return 0; 
}

    The pointer subtraction, and outputs the control code above, difficult to understand, p = the a,

    p is a pointer pointing to the first element of a, A0,

    So * p is equivalent to dereference a, a0 represents the object,

    And a0 this object is an array, it is understood as an array name, which is the address of the first element a0,

    * P represents i.e. pointer A00,

    Dereference and then * (* p) is the object of a00.

 

    Here a little around, more troublesome it is this pointer subtraction subtraction of the number of bytes per changed,

    When the direct subtraction p, increments the number of bytes is 20, corresponding to a0 share memory,

    * Subtraction of the p, increments the number of bytes is 4, corresponding to a00 share memory.

     

    So a good option to exclude ABC

    Option D * (* p + 2), p represents an array of a (a first array element address a0 in a),

          A0 * p represents the array (a first array element within an address a0 a00),

          * P + 2 represents the address a02, so * (* p + 2) represents a [0] [2].

          Verify the following:

#include <iostream>
#include <stdio.h>
using namespace std;

int main() {
	int a[4][5] = { 0, 0, 1, 0, 0,
		0, 0, 0, 0, 0,
		0, 0, 0, 0, 0,
		0, 0, 0, 0, 0 };
	int(*p)[5];
	p = a;


	cout << *(*p + 2) << endl;//输出1
	return 0;
}

Guess you like

Origin www.cnblogs.com/maider/p/11129048.html