3
I’m trying to make a simple function that counts diamonds, each diamond is given by a pair of '<' and '>'. But I’m trying to do it with pointers, but it’s not giving me the right result. I followed the "Simple teaching for pointers", and according to him I believe I am doing it correctly. Where is my mistake? Instead of showing the result, the number of diamonds, it always prints the same memory address.
They shall carry out the relevant tasks:
int main(int argc, char** argv) {
int casos; // número de casos de teste
int n;
int *diamantes; // aponta para número de diamantes
char vetor[1000]; //variável para armazenar a entrada
scanf("%d", &casos);
for (n = 0; n < casos; n++) {
limparBuffer();
ler(vetor);
contador(vetor, diamantes);
printf("%d\n", diamantes);
}
return (EXIT_SUCCESS);
}
int contador(char vetor[], int *d) {
int i, contEsq = 0, contDir = 0;
int n = 1;
for (i = 0; vetor[i] != '\0'; i++) {
if (vetor[i] == '<')
contEsq++;
else if (vetor[i] == '>')
contDir++;
}
if (contEsq > contDir)
d = &contDir;
else
d = &contEsq;
}
I ask what the problem is? Something can be easy to understand but it would be better for you to say what is happening with your code that shouldn’t. There’s something I’m not sure is wrong because it might be that you wanted what’s going on. When to the pointer I strongly advise to avoid it. Even if it’s just an example, I don’t think it makes sense to complicate a program to do something unnecessary. If you want to use the pointer, get something that needs a pointer.
– Maniero
Edited question, I agree that could make everything easier using just returns, but the intention is not only to understand, but rather to dominate this content. So I’m applying to the most diverse tasks where it wouldn’t be necessary, or even there are ways to do the same thing more easily. Grateful for the tip.
– pmargreff