An example of the application of a two-dimensional pointer to an array pointer

Source: Internet
Author: User

In fact, the multidimensional array of the computer system is actually finally implemented in the form of a one-dimensional array. In terms of a two-dimensional array of n x m, set its array to be named array. The pointer array points to an array that holds a series of pointers that point to the corresponding one-dimensional array, where our data is stored.

This array

is the I-pointer variable address, ARRAY[J] that is relative to the I-pointer variable offset j*sizeof (array type). Through this mechanism, the system accesses the contents of line I of the two-dimensional array and the column J. As you know, a pointer to a two-dimensional array is actually a pointer variable that points to the pointer variable address. So when you declare a pointer to a two-dimensional array, use the form int * * as array.

int main () {
int a[n][n];
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {
A[i][j]=i*n+j;
}
}
for (int i=0;i<n;i++)
cout<<* (* (a+i)) <<endl;
}

A two-dimensional array is actually a two-dimensional array pointer, and the output of this program is: 0 3 6

int main () {
int a[n][n];
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {
A[i][j]=i*n+j;
}
}
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {

cout<<* (* (a+i) +j) <<endl;

}
}
}

Here A is a pointer to the pointer, this function iterates through the entire array according to the line precedence, which is very well understood, * (A+i) represents the first address of line I, * (A+i) +j represents the address of the J element of line I, * (* (a+i) +j) denotes the element of row I, Column J, So we can iterate over the entire array. This is the line-first traversal of the array.

int main () {
int a[n][n];
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {
A[i][j]=i*n+j;
}
}
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {

cout<<* (* (a+j) +i) <<endl;

}
}
}

This is a column-first traversal of an array.

An example of the application of a two-dimensional pointer to an array pointer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.