This is a simple program to compute ages of people in the room. I am at the very initial stage, and now I see that I do not know which variables (I mean variables that I declare before scanf and then placeholders within scanf) to use for scanf; how to choose and apply a correct variable. Is there a resource that could explain in plain English these issues? Here is the program:
// Ages people by a year. Arrays
#include <stdio.h>
int main (void)
{
// determine number of people
int n;
do
{
printf("Number of people in room: ");
scanf ("%i", &n);
}
while (n<1); // get the number of people in the room, pass through user
// again and again until the user gives a positive integer
// declare array in which to store everyone's age
int ages[n];
int i;
for (i = 0; i < n; i++)
{
printf("Age of person #%i: ", i + 1); // person number 1, person number 2, etc
scanf ("%d", ages[i]); // store the age in the i-th part of the array ages
}
// report everyone's age a year hence
printf("Time passes...\n\n");
for (i = 0; i < n; i++)
{
printf(" A year from now person #%i will be %i years old.\n", i + 1, ages[i] + 1);
// we add 1 year to previous age
}
}
scanf("%d")
expects an address as an argument. Therefore, replace
scanf ("%d", ages[i]);
with
scanf ("%d", ages + i);
(or &ages[i]
but that's personal preference.)
scanf
expects pointer to some variable in order to change it's value - otherwise it will get some copy that won't affect the real variable.
this line : scanf ("%d", ages[i]);
dereference ages
and returns an integer, not a pointer to an integer. change it to be scanf ("%d", &ages[i]);
the &
will extract the memory address of ages[i]
and pass it as a pointer to scanf
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.