Counter adding an extra value in vector with pointer

0

I'm trying to finish an exercise that asks for 4 ages, and the output tells how many of the entered ages are greater than or equal to 18 but the counter always adds a value greater than 18 at the end and I do not understand the why.

#include <stdio.h>
#include <stdlib.h>

int main()
{
int vetor[3], *pvetor = &vetor[0],i,cont=0;
for(i=0;i<4;i++)
{
    printf("Introduza a %d idade: ",i+1);
    scanf("%d",&vetor[i]);
}
while(*pvetor != NULL)
{
    if(*pvetor >= 18)
        cont++;
    pvetor++;
}
printf("Das %d idades inseridas, %d sao maiores de idade.",4,cont);
}
    
asked by anonymous 01.07.2018 / 23:42

1 answer

3

If it is to receive 4 ages the array must have size 4. You can do the count already in the input. You do not need a pointer. If you know it's 4 ages you do not have to parameterize this. And this is C and not C ++.

#include <stdio.h>

int main() {
    int vetor[4], cont=0;
    for (int i = 0; i < 4; i++) {
        printf("Introduza a %da. idade: ", i + 1);
        scanf("%d", &vetor[i]);
        if (vetor[i] >= 18) cont++;
    }
    printf("Das 4 idades inseridas, %d sao maiores de idade.", cont);
}

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

    
01.07.2018 / 23:56