C + + using pointers to arrays as function parameters _c language

Source: Internet
Author: User
Tags first row

1. One-dimensional array names are passed as function parameters
An array name that corresponds to the address of the first element of the array;

Copy Code code as follows:

int a[10];
int *p;
P=a;
P=a and p=&a[0] are equivalent

Instance code:
Copy Code code as follows:

#include <iostream>
using namespace Std;
int main () {
int a[10]={1,2,3,4,5,6,7,8,9,10};
void Print (int *p, int n);
Print (a,10);
cout<<endl;
return 0;
}
void Print (int *p, int n) {
int i=0;
for (; i<n;i++) {
cout<<* (p+i) << "";
}
}

In the main function, the array name A is the value of the argument, that is, the value of &a[0] as the argument, and then in the print function, the pointer p to the INT variable is used to receive the passed value and to output the operation.

2. Multidimensional array names are passed as function parameters
In a two-dimensional array, array name A is a pointer to the first row a[0], meaning a=&a[0]; A[0] is a pointer to the first element a[0][0], that is to say a[0]=&a[0][0]

Instance code:

Copy Code code as follows:

#include <iostream>
using namespace Std;
int main () {
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
void Print (int (*p) [4]);
Print (a);
cout<<endl;
return 0;
}
void Print (int (*p) [4]) {
int i=0,j=0;
for (i=0;i<3;i++) {
for (j=0;j<4;j++) {
cout<<* (* (p+i) +j) << "";
}
}
}

P is a pointer to a[0], then P+i is a pointer to A[i], * (p+i) is a pointer to a[i][0, then * (P+i) +j is a pointer to a[i][j], so * (* (p+i) +j) is the value of a[i][j]

Related Article

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.