-2
I need to make this function count how many times a letter has been said in the string. However, the result always returns 0.
#include <stdio.h>
#include <string.h>
void contador(char palavra[], char letra[], int aux){
int qntd, i;
qntd = strlen(palavra);
for(i = 0; i < qntd; i++){
if(palavra[i] == letra){
aux++;
}
}
}
int main(){
char palavra[50], letra[1], aux;
printf("Digite um palavra: \n");
scanf(" %s", &palavra);
printf("Digite um letra a ser encontrada: \n");
scanf(" %s", &letra);
contador(palavra, letra, aux);
printf("O numero de vezes que a letra %s apareceu, foi de: %d", letra, aux);
}
Now he’s even returning values, but random values...
– Diovani Facco
– Diovani Facco
Since now on
contador
,aux
is a pointer toint
, you forgot to change theaux++
. Fixing this will probably work. Anyway, I don’t like this idea of passing the variableaux
by reference, as the function of thecontador
is to count the amount of times a letter occurs in a string, that amount should be its return value and not one of its arguments.– Vander Santos
There’s another mistake in
palavra[i] == letra
, forletra[]
was declared as an array in the function signaturecontador
and what’s worse in functionmain
also. Well, in main,scanf
is at least writing two characters in a declared array to fit only one, incontador
, if one insists on using an array, the comparison should bepalavra[i] == letra[0]
.– Vander Santos