c ++ as an array parameter passed is the value or address?

c ++ as an array parameter passed is the value or address?

Run the following program

STD namespace the using; 
int a [100] = {1,2,3,4,5,6,7,8,9}; 
void CIT (int B [100]) {// the address of a pass b, a modified equivalent modifications B 
	B [. 1] = 1113; // this is actually modified a [. 1]; 
	COUT << B [. 1] << endl; 
} 
int main () { 
	
	COUT << a [. 1] < <endl; // first element of the array output 
	cout << a << endl; // address output array 
	// char D = 'a'; 
	CIT (a); 
	COUT << a [. 1]; 
	return 0 ; 
}

  

 

 

 operation result:

1. Description: When a parameter array, the address is passed .

Modify the array in the function equivalent to modify the original array.

Note: The function can also be written

void cit (int b []) {// the address passed to a b, is equivalent to modifying a modified B 
	B [. 1] = 1113; // this is actually modified a [. 1]; 
	COUT << B [. 1 ] << endl; 
}

 

When passing, equal to the first address of the array pass passed, so may not be a set number of array elements.

If you want to pass the number of elements in the array, the array can be written

void cit (int b [], int n) {a // address will be passed b, corresponding to modify a modified B 
	B [. 1] = 1113; // this is actually modified a [. 1]; 
	COUT << B [. 1] << endl; 
}

 Call cit (a, 8)

2. If you guessed that address call cit (a + 4,4) of the array will pass over it? 

Yes, the fifth element a [4] address

STD namespace the using; 
int a [100] = {1,2,3,4,5,6,7,8,9}; 
void CIT (B int [], int n-) {// the address of a pass b, corresponding to a modification modified B 
	B [. 1] = 1113; // this is actually modified a [5], since b [0] corresponds to a [. 4]; 
	COUT << B [. 1] << endl ; 
} 
int main () { 
	
	COUT << a [. 1] << endl; // first element of the array output 
	cout << a << endl; // address output array 
	// char d = 'a'; 
	CIT (A + 4,4 &); 
	COUT << A [. 1] << endl; 
	COUT << A [. 5] << endl; 
	return 0; 
}

  Output:

 

 3. If you want to pass an array of values ​​to the function, or modify the value of the function array, how should I do it?

void cit(const int b[],int n)

So if you do not accidentally modify the array function, an error message will pop up

Use const means as read-only data in the array will function cit.

The following program will prompt an error

void cit (const int b [] , int n) {a // address will be passed b, corresponding to a modification modified b 
	b [. 1] = 1113; // this is actually modified a [5], because b [0] corresponds to a [. 4]; 
	COUT << B [. 1] << endl; 
}

 Summary: C ++ function in the digital processing, the number of data types must be submitted in the array, the starting position of the array element in the array and to it; conventional method is the name of the array (the first address) as a parameter, as the second array length parameter. 

 

Guess you like

Origin www.cnblogs.com/ssfzmfy/p/12520570.html