- How to define a struct with mixed types — char arrays and an int
- How to declare a struct variable and access its members
- How to read text into a char array with scanf and fgets
- How to print all three members with clean labels
- Why this pattern scales to arrays of students
Why a student struct
A student record has several fields: name, age, address, and probably marks, roll number, and a few more. If you stored each of these as a separate variable, you'd have a messy set of variables with no clear grouping. And if you had 100 students, you'd need 100 × 3 variables — that doesn't work.
A struct solves this by bundling related fields into one type. struct student holds a name, an age, and an address. You declare one variable of that type and it represents one student. You can pass that variable to a function, store it in an array, or return it from a function — the three fields stay together automatically.
This is the most common use of structs in real C programs: representing a record from a database, a row in a table, or an object from a domain. The pattern is always the same — define the fields, declare a variable, read the values, use the values.
💡 In one line: a student has a name (text), an age (number), and an address (text). Pack those three into one struct, read them from the user, print them back. That's the whole program.
Designing the struct
The struct has three members — two character arrays for text and one integer for age:
struct student {
char name[50];
int age;
char address[100];
};
The sizes matter. name[50] means a name can hold up to 49 characters plus the null terminator '\0'. That's enough for almost any name. address[100] allows 99 characters plus the terminator, which is enough for a full postal address. If you want more room, increase the numbers. If you want less, decrease them — but always remember the null terminator takes one byte.
The int age holds a whole number. Age is always a whole number in years, so int is correct. A float would waste space and add precision you don't need.
| Member | Type | Holds | Max length |
|---|---|---|---|
| name | char[50] | Student's name | 49 chars + '\0' |
| age | int | Age in years | — |
| address | char[100] | Postal address | 99 chars + '\0' |
One important thing to know: name and address are arrays. You cannot assign to them with = after the struct is declared. s.name = "Rahul"; is a compile error. You have to use strcpy, or read into them with scanf, or initialize them at declaration time. This is the most common beginner mistake with structs — and we'll cover it in the explanation.
Complete C Program
Program: read and display one student record
#include <stdio.h>
struct student {
char name[50];
int age;
char address[100];
};
int main(void) {
struct student s;
printf("Enter name: ");
scanf("%49s", s.name);
printf("Enter age: ");
scanf("%d", &s.age);
/* Clear the newline left by the previous scanf */
getchar();
printf("Enter address: ");
fgets(s.address, sizeof(s.address), stdin);
printf("\n--- Student Record ---\n");
printf("Name : %s\n", s.name);
printf("Age : %d\n", s.age);
printf("Address : %s", s.address);
return 0;
}
And here's a simpler version that uses scanf for all three fields — fine if the address doesn't contain spaces (e.g., "Mumbai" instead of "Andheri West, Mumbai"):
Variant: single-word address, scanf only
#include <stdio.h>
struct student {
char name[50];
int age;
char address[100];
};
int main(void) {
struct student s;
printf("Enter name, age, address: ");
scanf("%49s %d %99s", s.name, &s.age, s.address);
printf("\n--- Student Record ---\n");
printf("Name : %s\n", s.name);
printf("Age : %d\n", s.age);
printf("Address : %s\n", s.address);
return 0;
}
And here's a third version that initializes the struct directly — useful if the data is fixed and you don't need user input:
Variant: hard-coded student
#include <stdio.h>
struct student {
char name[50];
int age;
char address[100];
};
int main(void) {
struct student s = {"Rahul Sharma", 20, "Mumbai, India"};
printf("--- Student Record ---\n");
printf("Name : %s\n", s.name);
printf("Age : %d\n", s.age);
printf("Address : %s\n", s.address);
return 0;
}
All three versions use the same struct. The differences are just how the data gets into the struct — from the user (with scanf or fgets) or hard-coded in the declaration. The struct definition and the print code are identical.
Program Output
For the first version (fgets for address, so spaces are allowed):
Enter name: Rahul
Enter age: 20
Enter address: 42 MG Road, Andheri West, Mumbai
--- Student Record ---
Name : Rahul
Age : 20
Address : 42 MG Road, Andheri West, Mumbai
For the second version (scanf only, so the address can't contain spaces):
Enter name, age, address: Rahul 20 Mumbai
--- Student Record ---
Name : Rahul
Age : 20
Address : Mumbai
For the third version (hard-coded):
--- Student Record ---
Name : Rahul Sharma
Age : 20
Address : Mumbai, India
Notice that the first version keeps the entire address (with spaces), while the second version stops at the first space. That's the difference between fgets and scanf("%s") — fgets reads the whole line, scanf stops at whitespace. For addresses, use fgets.
Step-by-Step Explanation
Let's walk through the key pieces.
1. The struct definition
struct student { char name[50]; int age; char address[100]; }; creates a new type. The members are laid out in the order they appear in the declaration — that order matters for initializer lists. If you write {"Rahul", 20, "Mumbai"}, the first value goes to name, second to age, third to address.
2. Declaring a variable
struct student s; creates one variable named s of type struct student. At this point the members hold garbage values. That's why you must fill them before reading them.
3. Reading the name with scanf
scanf("%49s", s.name) reads a whitespace-delimited string into the name array. The 49 in %49s is a width limit — it reads at most 49 characters, leaving one byte for the null terminator. That's a safety measure. Without it, a long input could overflow the buffer. Note that s.name does not need an & because the array name is already a pointer to its first element.
4. Reading the age
scanf("%d", &s.age) reads an integer into the age member. The & is required here because age is a scalar (int), not an array. That's the rule: arrays don't need &, scalars do.
5. Reading the address with fgets
fgets(s.address, sizeof(s.address), stdin) reads a whole line (including spaces) into the address array. The second argument is the buffer size — sizeof(s.address) is 100, so at most 99 characters plus the null terminator. The third argument is the stream, which for console input is stdin. This is the right choice for addresses, because addresses contain spaces.
6. The getchar() in between
When you press Enter after typing the age, scanf reads the digits but leaves the newline (\n) in the input buffer. If you then call fgets, it sees the newline and immediately returns — with an empty address. The getchar() consumes that leftover newline so fgets can read the actual address. This is a standard fix, and it's worth knowing by heart because it comes up every time you mix scanf and fgets.
7. Printing the record
Each member is printed with the right format specifier — %s for the char arrays, %d for the int. The labels ("Name :", "Age :", "Address :") make the output read like a form, which is exactly what a student record should look like. The fgets version already includes a newline at the end of the address (from the Enter key), so you don't need to add \n after %s for that line — but it's harmless if you do.
8. Why not assign directly?
You might think s.name = "Rahul"; would work — it doesn't. Arrays are not assignable in C. You have to use strcpy(s.name, "Rahul") from <string.h>, or read into the array with scanf/fgets, or initialize at declaration. This is the single most common mistake when learning structs. Get it into your head early.
9. Why this scales to many students
The real power of a struct shows up when you want an array of students. struct student class[60]; gives you 60 student records, each with its own name, age, and address. To access the name of the third student, you write class[2].name. That's it — one line per field, no parallel arrays, no confusion about which index maps to which value. This is why structs are so useful for record-oriented data.
🎯 Remember this: define the struct with all its fields, one type per field. Declare a variable. Use scanf for short fields and fgets for text that may contain spaces. Print each member with the right format specifier. Never assign a string directly to a char array — use strcpy or scanf.
Frequently Asked Questions
1. Why use char arrays instead of char pointers?
Because char arrays hold the actual characters inside the struct. A char pointer would just hold an address — and if you assigned it to a string literal, the struct would point into read-only memory. For a record that you want to copy, modify, or save to a file, an array is the right choice. Pointers are useful when strings are shared or very large, but for a student record the array is simpler and safer.
2. What's the difference between scanf("%s") and fgets for the address?
scanf("%s") stops at the first whitespace, so "Andheri West, Mumbai" becomes just "Andheri". fgets reads the whole line, so you get the full address. For a name, scanf is fine (names usually don't have spaces). For an address, use fgets. Just remember the getchar() fix so fgets doesn't immediately see the leftover newline from the previous scanf.
3. Why does the address include a newline at the end?
Because fgets includes the newline character in the buffer when the user presses Enter. So s.address ends with '\n'. When you print with printf("%s", s.address), that newline is already there — you don't need to add \n at the end of the format string. If you want to remove it, use s.address[strcspn(s.address, "\n")] = '\0'; after reading.
4. Why is the & not needed for name and address in scanf?
Because arrays decay to pointers when passed to functions. s.name is equivalent to &s.name[0] — a pointer to the first character. scanf already expects a pointer for %s, so passing the array name works. For %d (used with age), scanf expects a pointer to the int, so you must write &s.age. The rule: arrays don't need &, scalars do.
5. Can I store multiple students in one struct?
No — one struct variable is one record. For multiple students, use an array of structs: struct student class[60]; gives you 60 student records. Access them with class[0].name, class[1].name, etc. That's the standard pattern for record-oriented data. A loop reads each record, a loop prints each record, and everything stays organized.
6. Why is the width limit %49s important in scanf?
Because without it, a user could type more characters than the buffer holds, and scanf would write past the end of the array — a buffer overflow. That's a bug and a security risk. The 49 in %49s tells scanf "read at most 49 characters." Since the array is 50 bytes, that leaves room for the null terminator. Always use a width limit with scanf %s. Always. It's a habit worth building from the very first program.
💡 Tip: After this, try storing three students in an array and reading/printing them in a loop. Then try adding a float marks[5] member for five subject marks, and compute the average. Then try adding a function void print_student(struct student s) that prints all fields — you'll see how passing a struct to a function keeps the code clean. Each of these builds on the same pattern: define the fields, read them, use them.