I'm learning C, but I find those vague compiler error messages increasingly frustrating. Here's my code:
char getkey (int minimo, int maximo, int alphalen, int index, char alpha[])
{
int cociente, residuo, cont;
int i = 0;
char cand[maximo+1];
char candidate[maximo+1];
while (index != 0)
{
cociente = index / alphalen;
residuo = index%alphalen;
cand[i] = residuo;
index = cociente;
i+=1;
}
for (cont=i-1; cont>=0; cont--)
{
int pos = cand [cont];
candidate[i] = alpha[pos];
}
return candidate;
}
This generates one warning:
Can someone explain these warning?
Your local variable candidate is an array of char. When you say
return candidate;
you return a pointer to char. (This is due to the very close relationship between arrays and pointers in C, which you will have to learn about if you don't know yet.) But you've stated that your function getkey returns a char, not a pointer-to-char.
You need to make the function's return value match its type. You might want change the return statement so it returns a single char. If you want to have the function return a whole string, you could change its declaration to char *getkey(), but in that case you'll also have to take care of the allocation of the candidate array.
Here's what the warning means. You tried to return a pointer. The function is supposed to return a character, which is represented as a small integer. The compile is willing to try to convert the pointer to an integer, in case that's what you really want to do, but since that's not usually a good idea, it warns you. Indeed, in this case the warning tells you that you probably made a mistake.
getkey has been declared to return a char, but you're trying to return candidate which is a char array.
You probably meant to return one of the elements in the array, i.e. something like candidate[x].
The reason for the error message saying "pointer" instead of "array" is that the compiler is converting candidate to a pointer to the first element in the array, which happens implicitly in some contexts, for example when returning, since arrays can't be returned (or passed as parameters) by value in C (see What is array decaying?).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With