Counter adding an extra value to the vector with pointer

Asked

Viewed 76 times

0

I’m trying to finish an exercise that asks for 4 ages and the output tells how many of the inserted ages are greater than or equal to 18 but the counter always adds a value greater than 18 at the end and I don’t understand 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);
}
  • This code does not seem to do what is described, the error is in the code or in the description?

  • I was wrong in the description the purpose is to tell how many ages are greater than or equal to 18*

  • No, this is written in the description. Without knowing what the problem is, there is no way to know what the solution is.

  • I’ve corrected the description

1 answer

3

If it is to receive 4 ages o array should have size 4. You can count already on the input. No need for pointer. If you know it is 4 ages you have no reason to parameterize this. And this is C, 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • But an array starts from 0 so putting 3 would leave 4 spaces not?

  • No, when you declare you have to say the size, not what is the last element.

  • I realize that it makes no sense to use pointers in this way but the goal of the exercise is to use pointers to solve the problem and change the size of the array did not change the final result however put conta-- after finishing the while cycle works but I would like to know why the counter is adding an extra value at the end of the array, that’s all..

  • Any exercise that requires doing something that should not be is a bad exercise and stuck by definition and is exercising for evil. Even in fact this is in the code and has zero function in it, nor to cause problem it is serving. The counter is not adding anything else.

  • 1

    The OP instead of accepting his answer, preferred to self-destruct?

  • 1

    @Victorstafusa apparently yes, that’s the state of things nowadays, nobody commits, it’s all fleeting

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.