Hi I have a trouble trying to manage a the following array.
I have initialized this pointer int* coordenadasFicha = new int[2];
and I want to asign the two int
asking the user for the numbers.
The trouble appears when I call pedirCoordenadasFicha(coordenadasFicha);
Clion recomends me cast coordenadasFicha
to int**
but I need to use it as a simple pointer. pedirCoordenadasFicha() basically does this:
void pedirCoordenadasFicha(int* coordenadasFicha[2]){
std::cin >> *coordenadasFicha[0];
std::cin >> *coordenadasFicha[1];}
All help is welcome
An int*
(a pointer-to-int) and an int*[]
(an array of pointer-to-int) are two different things. And actually, in a function parameter, int* coordenadasFicha[2]
is actually passed as int**
(pointer to pointer-to-int), because an array decays into a pointer to its 1st element.
In your case, you are creating coordenadasFicha
as an dynamic array of int
s, but your function is expecting an array of int*
pointers instead.
So, to do what you are attempting, you would need to do either this:
void pedirCoordenadasFicha(int* coordenadasFicha){
std::cin >> coordenadasFicha[0];
std::cin >> coordenadasFicha[1];
}
int* coordenadasFicha = new int[2];
pedirCoordenadasFicha(coordenadasFicha);
...
delete[] coordenadasFicha;
Or this:
void pedirCoordenadasFicha(int* coordenadasFicha[2]){
std::cin >> *coordenadasFicha[0];
std::cin >> *coordenadasFicha[1];
}
int** coordenadasFicha = new int*[2];
for(int i = 0; i < 2; ++i) {
coordenadasFicha[i] = new int;
}
pedirCoordenadasFicha(coordenadasFicha);
...
for(int i = 0; i < 2; ++i) {
delete coordenadasFicha;
}
delete[] coordenadasFicha;
Or, just get rid of new
altogether, and pass the array by reference:
void pedirCoordenadasFicha(int (&coordenadasFicha)[2]){
std::cin >> coordenadasFicha[0];
std::cin >> coordenadasFicha[1];
}
int coordenadasFicha[2];
pedirCoordenadasFicha(coordenadasFicha);
...