How to Declare Structure in C: Syntax and Examples
In C, you declare a structure using the
struct keyword followed by the structure name and a block of member variables inside braces. For example, struct Person { int age; char name[50]; }; defines a structure named Person with two members.Syntax
A structure in C is declared using the struct keyword, followed by the structure name and a block containing member declarations inside curly braces. Each member has a type and a name, separated by semicolons. The declaration ends with a semicolon.
- struct: keyword to define a structure
- StructureName: the name you give to the structure
- { ... }: braces containing member variables
- Members: variables inside the structure with types
- ;: semicolon ends the declaration
c
struct StructureName {
type member1;
type member2;
// more members
};Example
This example shows how to declare a structure named Person with two members: age (an integer) and name (a string). It also shows how to create a variable of this structure and print its values.
c
#include <stdio.h>
struct Person {
int age;
char name[50];
};
int main() {
struct Person person1;
person1.age = 30;
// Copying string safely
snprintf(person1.name, sizeof(person1.name), "%s", "Alice");
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
return 0;
}Output
Name: Alice
Age: 30
Common Pitfalls
Common mistakes when declaring structures in C include:
- Forgetting the semicolon
;after the closing brace of the structure declaration. - Not using the
structkeyword when declaring variables of the structure type (unless usingtypedef). - Incorrectly copying strings into character arrays inside structures (use
strcpyorsnprintfinstead of direct assignment).
c
/* Wrong: Missing semicolon after structure declaration */ struct Person { int age; char name[50] } // <-- Missing semicolon here /* Correct: */ struct Person { int age; char name[50]; };
Quick Reference
Remember these tips when working with structures in C:
- Always end the structure declaration with a semicolon.
- Use
struct StructureName variable;to declare variables. - Use
typedefto simplify variable declarations if desired. - Access members with the dot operator:
variable.member.
Key Takeaways
Use the
struct keyword followed by braces and members to declare a structure.Always end the structure declaration with a semicolon to avoid syntax errors.
Declare variables with
struct StructureName variable; unless using typedef.Access structure members using the dot operator, like
variable.member.Use safe string functions like
snprintf to assign strings to character arrays in structures.