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
CodePudding user response:
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);
...
CodePudding user response:
I need to use it as a simple pointer.
int* coordenadasFicha[2]
is not a "simple pointer", if by simple pointer you mean int*
. In any other context, coordenadasFicha
would be an array of pointers, but function parameters aren't arrays in C ; the parameter is adjusted to be a pointer to element of such array. The element of the array is int*
and a pointer to int*
is int**
. Hence the type of coordenadasFicha
is int**
(after adjustment).
If you want a parameter to have the type int*
, then you must declare the parameter to have the type int*
and not some other type. Example:
void
pedirCoordenadasFicha(int* coordenadasFicha)
{
std::cin >> coordenadasFicha[0];
std::cin >> coordenadasFicha[1];
}