How to properly use struct inside for loop?

Viewed 612

Task: We need to create 7 structure objects called parent[1-7] using loops. Then make user input for their name, age, child name. Afterwards 1) print name of the parent that has the biggest family. 2)print longest child name for the parents with shortest name (compared to other) I know, sounds confusing already. And 3) Print out all the given info of parents (name, age, child name/names) that are older than average of 7 parents age.

Problem: I bumped into the trouble that I can't even setup this right for program to scan user input. I have added a new struct object and scanf for user to insert how many kids he has, for easier access later on, but it keeps crashing when I enter that number for example 2 or 3 kids. To be honest, I have no idea how to do other parts of this task.

This is how program looks at the moment (I'm on my first year in University, so I expect that I made some mistakes):

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


int max=3;
int j=0;


struct parents
{
    char name[30];
    int age;
    int kid_count;
    char kid_name[30];
};

int main()
{
  for(j=0; j<max; j++)
  {
    struct parents parent[7];
    parent[j].name;
    parent[j].age;
    parent[j].kid_count;
    parent[j].kid_name;


    printf("Parent %d Enter parent name \n",j+1);
    scanf(" %s", &parent[j].name);


    printf("Parent %d Enter parent age \n",j+1);
    scanf(" %d", &parent[j].age);


    printf("Parent %d Enter how many kids he has \n",j+1);
    scanf(" %d", &parent[j].kid_count);


    printf("Parent %d child name \n",j+1);
    scanf(" %s", &parent[j].kid_name);
  }

  return 0;
}
1 Answers
for(j=0; j<max; j++)
{
    struct parents parent[7];

You're declaring an array of 7 structures here, each and every time through the loop. Because it's declared on the stack in the scope of the loop's body, that array will also go away each and every time through the loop. But you only ever use one of the structures, i.e. the one at index j, on each iteration.

What you probably mean to do instead is to declare the array outside the scope of the loop, so that it persists after the loop is done.

    parent[j].name;
    parent[j].age;
    parent[j].kid_count;
    parent[j].kid_name;

These lines don't seem to do anything. Did you mean to assign a value to each field here? The next thing you do is to write values into those fields using scanf(), so any value that you might set here would be overwritten. Probably best to just delete these lines.

 return 0;
}

Once the loop is done, nothing else happens. Even if you move the array of parent structures outside the loop, it's going to go out of scope at this point without anything being done with it. To make that array useful, you need to use it. Maybe you just haven't gotten to that part yet?

Related