Miguel, it turns out that &numaboa[2]
is the address of the index cell 2
. That is, &numaboa[0]
gives the same as numaboa
(address of the first cell), &numaboa[1]
gives in the same as numaboa+1
(address of the second cell) and &numaboa[2]
gives in the same as numaboa+2
, points to a cell that does not even exist.)
In addition, the int v[]
parameter indicates that v
is a pointer because the array (or vector) symbol is treated as a constant pointer that is worth the address of the first cell, that is, the int *vetor[2]
indicates that vetor
is a pointer type for another pointer, this is for integer.
So, know that if you intend to use cell values then you can pass numaboa
as an argument to a parameter of type int*
(that is, function can be void somadiferenca( int *vetor )
or void somadiferenca( int vetor[] )
or void somadiferenca( int vetor[2] )
) and then access the two cells using vetor[0]
and vetor[1]
.
A valid way to implement everything is the following, which somadiferenca
accepts pointer, somadiferenca(numaboa)
actually does pointer passing and inside the function makes cell access via pointer parameter.
#include <iostream>
using namespace std;
int somadiferenca( int *vetor ){
int x = vetor[0] + vetor[1] ;
int y = vetor[0] - vetor[1] ;
if( y<0 ){
cout << x << endl << (-y) ;
}
else {
cout << x << endl << y;
}
}
int main(){
int numaboa[2] ;
cin >> numaboa[0] ;
cin >> numaboa[1] ;
somadiferenca( numaboa ) ;
return 0 ;
}
Remembering some basic things:
1) int numaboa[2]
is the definition of two temporary local cells in the function that are consecutively allocated in memory (execution stack);
2) numaboa
is the constant (unchanging) pointer that always points to these two cells ( numaboa
is the address of the first, via index addresses other) seeing them as array;
3) numaboa[i]
is an array cell and numaboa+i
is the same as &(numaboa[i])
, ie the address of the cell numaboa[i]
;
4) Parameters int vector[]
and int *vector
are the same, both pointers, after all symbols of arrays like vetor
allocated in the stack are treated as pointers.
Okay?
Any questions?