0

I'm studying pointers and in this code, trying to use pointers to store 10 int values and 10 char values in the memory and, after that, count every age that as above 40 years old and every Male (M).

But, when the code is compiled, he just "jumps" the parts where is supposed to ask the char values. What am I missing here?

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

int main(int argc, char *argv[])
{
    int *pAge, nBigger, nMale;
    char *pGender;
    int i;

    pAge = (int*)calloc(10, sizeof(int));
    pGender = (char*)calloc(10, sizeof(char));

    if (pAge != NULL && pGender != NULL) {

        for (i = 0; i < 10; i++)
        {
            printf("\n%d. Type your age: ", i + 1);
            scanf("%d", &pAge[i]);

            if (pAge[i] > 40)
            {
                nBigger++;
            }

            printf("\n%d. Type your gender (M / F): ", i + 1);
            scanf("%c", &pGender[i]);

            if (toupper(pGender[i]) == 'M')
            {
                nMale++;
            }
        }

    }
    else {
        printf("Out of memory");
        exit(1);

    }

    printf("\nBigger than 40 y/o: %d", nBigger);
    printf("Male gender: %d", nMale);

    free(pAge);
    free(pGender);

    return 0;
}
Alex Lop.
  • 6,810
  • 1
  • 26
  • 45

1 Answers1

0

After you read an int using scanf("%d", &pAge[i]); a newline ('\n') is still in stdins buffer. The next scanf("%c", &pGender[i]); reads that '\n' without giving you the chance to actually make any input.

Use

scanf(" %c", &pGender[i]);
       ^

To read a character but with skipping every whitepace before.

Also your variables nBigger and nMale are not initialized.

Swordfish
  • 12,971
  • 3
  • 21
  • 43