问题
I got a compiler error:
main.cpp|59|error: invalid conversion from 'int' to 'int*' [-fpermissive]|
The offending line is
int *pComienzo = vector, *pFinal = vector[nElementos-1];
Why there is an error? Can someone help me?
Below is my code:
#include <iostream>
#include <ctype.h>
using namespace std;
const unsigned short int MAX_VAL = 10;
int LongitudCadena(char*);
int BuscarCaracter(char *cadena, char caracter);
void Ordenar(int *vector, int nElementos, bool ascendente);
int main()
{
char *cadena = "asdasd";
cout << LongitudCadena(cadena) << endl;
cout << BuscarCaracter(cadena, 'a') << endl;
int iArray[] = {5,4,3,2,1};
Ordenar(iArray, 5, 1);
cout << iArray << endl;
return 0;
}
int LongitudCadena(char *cadena)
{
char *c = cadena;
for(int i = 0; i < MAX_VAL; i++)
{
if (c[i] == 0) break;
cadena++;
}
return cadena - c;
}
int BuscarCaracter(char * cadena, char caracter)
{
char *pCadena = cadena;
for (int i = 0; i < MAX_VAL; i++)
{
pCadena++;
if (toupper(cadena[i]) == toupper(caracter))
return pCadena- cadena;
}
return -1;
}
void Ordenar(int *vector, int nElementos, bool ascendente)
{
int *pComienzo = vector, *pFinal = vector[nElementos-1];
if (ascendente)
{
for (int i = 0; i < nElementos; i++)
{
for (; pComienzo < pFinal; pComienzo++, pFinal--)
{
if (*pComienzo > *pFinal)
{
*pComienzo += *pFinal;
*pFinal -= *pComienzo;
*pComienzo -= *pFinal;
}
}
}
}
}
I'm learning...
回答1:
Your error is in this line:
int *pComienzo = vector, *pFinal = vector[nElementos-1];
The reason for this is that vector is an int*, but vector[nElementos - 1] is a regular int. Thus the declaration
int *pFinal = vector[nElementos - 1];
is trying to assign the integer value at the last index of vector to the pointer pFinal, hence the compiler error.
To fix this, you may want to do either
int *pFinal = &vector[nElementos - 1];
which makes pFinal point to the last element of vector, or
int *pFinal = vector + (nElementos - 1);
which accomplishes the same thing using pointer arithmetic.
That said, since you're working in C++, why not use the provided std::vector type and avoid working with pointers altogether?
Hope this helps!
回答2:
vector is a pointer, but subscripting it as vector[nElementos-1] dereferences it to simply an int. What it looks like you want is instead
int *pComienzo = vector, *pFinal = &(vector[nElementos-1]);
回答3:
An array access/subscript (i.e., a[i] where a is an array/pointer and i is an integer) is an expression with the type being the thing you have in the array.
Simply use the address-of operator & to store the address in the pointer:
int *pComienzo = vector, *pFinal = &vector[nElementos-1];
回答4:
You forgot &. vector[nElementos-1] is the value, while you need an address for pFinal.
Either *pFinal = &(vector[nElementos-1]) or *pFinal = vector + nElementos-1.
来源:https://stackoverflow.com/questions/9167834/compiler-error-invalid-conversion-from-int-to-int-fpermissive