Miguel, it turns out that &numaboa[2]
is the address of the index cell 2
. You mean, &numaboa[0]
is the same as numaboa
(address of the first cell), &numaboa[1]
is the same as numaboa+1
(address of the second cell) and &numaboa[2]
is the same as numaboa+2
(I mean, it points to a cell that doesn’t even exist).
In addition, the parameter int v[]
indicates that v
is a pointer because the array symbol (or vector) is treated as a constant pointer that is worth the address of the first cell, that is, the parameter int *vetor[2]
indicates that vetor
is a pointer type to another pointer, this for whole.
So, know that if the intention is to use the values of the cells then you can pass numaboa
as argument in a type parameter 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 as follows, that somadiferenca
accepts pointer, the somadiferenca(numaboa)
in fact does pointer pass and within the function does cell access via pointer type 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 allocated consecutively in memory (execution stack);
2) numaboa
is the constant (unalterable) pointer that always points to these two cells (numaboa
is worth the address of the first, via index is addressed to others) seeing them as array;
3) numaboa[i]
is an array cell and numaboa+i
is the same as &(numaboa[i])
, i.e., the cell address numaboa[i]
;
4) Parameters int vector[]
and int *vector
are the same thing, both pointers, after all arrays symbols like vetor
allocated on the stack are treated as pointers.
Okay?
Any doubt?
I found your code organization very confusing. I believe the argument of
somadiferenca
should only be a two-position vector, passing as parameter the variablenumaboa
– Jefferson Quesado
The idea was to test the use of pointers along with arrays, but it didn’t work. I want to understand why it didn’t work with the pointer, but I could do without it easily. Thanks for the answer, Jefferson ^^
– MiguelTeixeira