0% found this document useful (0 votes)
23 views8 pages

Structure Definition

Uploaded by

YATHAARTH THAPAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views8 pages

Structure Definition

Uploaded by

YATHAARTH THAPAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Structure Definition

A structure in C is a user-defined data type that allows grouping of variables of different data
types under a single name. It is defined using the struct keyword.

Example:

struct Student {
int id;
char name[50];
float grade;
};

In this example, Student is a structure containing an integer (id), a character array (name),
and a float (grade).

2. Structure Initialization

Structures can be initialized in two ways: when defining variables or by assigning values to
members later.

Example:

struct Student s1 = {1, "Alice", 85.5};


s1.id = 2;
strcpy(s1.name, "Bob");
s1.grade = 90.0;

Here, s1 is initialized with values at the time of declaration, and then values are updated
individually.

3. Accessing Structures

Structure members are accessed using the dot (.) operator. If you have a pointer to a
structure, the arrow (->) operator is used.

Example:

printf("ID: %d\n", s1.id);


printf("Name: %s\n", s1.name);
printf("Grade: %.2f\n", s1.grade);

struct Student *ptr = &s1;


printf("ID using pointer: %d\n", ptr->id);

4. Nested Structures

A structure can contain another structure as a member, known as a nested structure.

Example:

struct Date {
int day, month, year;
};

struct Student {
int id;
char name[50];
struct Date dob; // Nested structure
};

struct Student s2 = {1, "Charlie", {12, 5, 2000}};

In this example, Student has a Date structure as a nested member.

5. Arrays of Structures

You can create an array of structures to store data for multiple entities.

Example:

struct Student students[3] = {


{1, "Alice", 85.5},
{2, "Bob", 90.0},
{3, "Charlie", 88.5}
};

for (int i = 0; i < 3; i++) {


printf("Student %d: %s\n", students[i].id, students[i].name);
}

This example shows an array of Student structures to store information about multiple
students.

6. Structures and Functions

Structures can be passed to functions by value or by reference (using pointers).

Example:

void displayStudent(struct Student s) {


printf("ID: %d\nName: %s\nGrade: %.2f\n", s.id, s.name, s.grade);
}

displayStudent(s1);

Passing by reference is more efficient, especially for large structures:

void updateGrade(struct Student *s, float newGrade) {


s->grade = newGrade;
}

updateGrade(&s1, 95.0);

7. Self-Referential Structures
A self-referential structure contains a pointer to a structure of the same type, which is
commonly used in linked lists.

Example:

struct Node {
int data;
struct Node *next; // Self-referential
};

struct Node n1, n2;


n1.data = 10;
n1.next = &n2;
n2.data = 20;
n2.next = NULL;

8. Unions

A union is similar to a structure but only allows one member to hold a value at any given
time, saving memory.

Example:

union Data {
int i;
float f;
char str[20];
};

union Data d;
d.i = 10;
printf("i: %d\n", d.i);
d.f = 220.5;
printf("f: %.2f\n", d.f); // i is now undefined

9. Typedef

typedef allows creating an alias for a data type, making code easier to read and manage.

Example:

typedef struct {
int id;
char name[50];
} Student;

Student s3;
s3.id = 3;
strcpy(s3.name, "David");

This way, Student can be used directly as a type without using struct.

10. Enumerations
An enumeration defines a list of named integer constants, often used to represent states or
options.

Example:

enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday,


Sunday };

enum Day today = Wednesday;


if (today == Wednesday) {
printf("It's midweek!\n");
}

FILE HANDLING
1. Command Line Arguments

Command line arguments are used to pass arguments to a program from the command line. In
C, these arguments are accessed through main() function parameters int argc (argument
count) and char *argv[] (argument vector).

 argc stores the number of arguments, including the program name.


 argv[] is an array of strings representing each argument.

Example:

#include <stdio.h>

int main(int argc, char *argv[]) {


printf("Number of arguments: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}

Usage:

$ ./program arg1 arg2

Output:

Number of arguments: 3
Argument 0: ./program
Argument 1: arg1
Argument 2: arg2
2. File Modes

File modes determine how a file is opened, such as for reading, writing, or appending.
Common file modes in C include:

 "r" - Open for reading.


 "w" - Open for writing (creates or overwrites).
 "a" - Open for appending.
 "r+" - Open for reading and writing.
 "w+" - Open for reading and writing (creates or overwrites).
 "a+" - Open for reading and appending.

Example:

FILE *file = fopen("example.txt", "r");


if (file == NULL) {
printf("File could not be opened.\n");
}

3. Basic File Operations: Read, Write, and Append

In C, file operations are performed using standard functions like fopen, fclose, fprintf,
fscanf, fgets, fputs, etc.

Writing to a File

Example:

#include <stdio.h>

int main() {
FILE *file = fopen("file.txt", "w");
if (file == NULL) {
printf("File could not be opened.\n");
return 1;
}
fprintf(file, "Hello, World!\n");
fclose(file);
return 0;
}

This opens file.txt in write mode and writes "Hello, World!" to it.

Reading from a File

Example:

#include <stdio.h>

int main() {
FILE *file = fopen("file.txt", "r");
char buffer[100];
if (file == NULL) {
printf("File could not be opened.\n");
return 1;
}
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file);
return 0;
}

This reads lines from file.txt and prints them to the console.

Appending to a File

Example:

#include <stdio.h>

int main() {
FILE *file = fopen("file.txt", "a");
if (file == NULL) {
printf("File could not be opened.\n");
return 1;
}
fprintf(file, "This is an appended line.\n");
fclose(file);
return 0;
}

This appends text to the end of file.txt.

4. Scope and Lifetime of Variables

 Scope: The region in the code where a variable is accessible.


o Local Scope: Variables declared within a function and accessible only within
that function.
o Global Scope: Variables declared outside all functions and accessible
throughout the program.
o Block Scope: Variables declared within a block {}.
 Lifetime: How long a variable exists in memory.
o Automatic (local): Default storage for local variables; they exist only during
function execution.
o Static: Variables with static keyword retain their value between function
calls.
o Global: Global variables exist throughout the program execution.

Example:

#include <stdio.h>

int global_var = 10; // Global scope

void function() {
int local_var = 20; // Local scope
static int static_var = 30; // Retains value between calls
printf("Global: %d, Local: %d, Static: %d\n", global_var, local_var,
static_var);
static_var++;
}

int main() {
function();
function();
return 0;
}

Output:

Global: 10, Local: 20, Static: 30


Global: 10, Local: 20, Static: 31

5. Multi-File Programming

In multi-file programs, code is split across multiple files for better organization and
modularity.

For example, consider a program split into two files: main.c and helper.c. A header file
(helper.h) is also created to share function declarations.

helper.h:

#ifndef HELPER_H
#define HELPER_H

void displayMessage();

#endif

helper.c:

#include <stdio.h>
#include "helper.h"

void displayMessage() {
printf("Hello from helper.c!\n");
}

main.c:

#include "helper.h"

int main() {
displayMessage();
return 0;
}

Compilation:
gcc main.c helper.c -o program
./program

Output:

Hello from helper.c!

You might also like