0% found this document useful (0 votes)
125 views

Structure in C

1. A C structure allows grouping of related data types under one name and can contain variables of different data types. 2. Structures are useful for organizing related data like the properties of a book or student records. 3. Structure pointers store the address of a structure variable in memory and can be used to access structure members using the arrow operator ->.

Uploaded by

gafos82267
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
125 views

Structure in C

1. A C structure allows grouping of related data types under one name and can contain variables of different data types. 2. Structures are useful for organizing related data like the properties of a book or student records. 3. Structure pointers store the address of a structure variable in memory and can be used to access structure members using the arrow operator ->.

Uploaded by

gafos82267
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

STRUCTURE IN C

The structure in C is a user-defined data type that can


be used to group items of possibly different types into
a single type. The struct keyword is used to define
the structure in the C programming language. The
items in the structure are called its member and they
can be of any valid data type.

USES OF STRUCTURE
Structure in C programming is very helpful in cases where we
need to store similar data of multiple entities. understand the
need for structures with a real-life example. Suppose you need to
manage the record of books in a library. Now a book can have
properties like book_name, author_name, and genre

In order to store such a wide variety of data types under


one single variable, we use the Structure Data type.
The structure is a user-defined data type that stores
data elements of similar or different types and different
lengths. Structures are used to represent a record of
various other data elements.
A regular structure also creates a sense of familiarity
and control that can reduce your stress levels and help
you feel more in control of your time and life generally.
C structures are used for the following:
1. The structure can be used to define the custom data types that can be used to
create some complex data types such as dates, time, complex numbers, etc.
which are not present in the language.
2. It can also be used in data organization where a large amount of data can be
stored in different fields.
3. Structures are used to create data structures such as trees, linked lists, etc.
4. They can also be used for returning multiple values from a function.

A Structure is a data structure that can contain


variables of different data types. An Array is a data
structure that can only contain variables of the same
data type.

C Structure Declaration
We have to declare structure in C before using it in our program. In
structure declaration, we specify its member variables along with
their datatype. We can use the struct keyword to declare the
structure in C using the following syntax:
Syntax

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
The above syntax is also called a structure template or structure
prototype and no memory is allocated to the structure in the
declaration.
C Structure Definition
To use structure in our program, we have to define its instance. We can do
that by creating variables of the structure type. We can define structure
variables using two methods:

1. Structure Variable Declaration with Structure Template

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template

// structure declared beforehand

struct structure_name variable1, variable2 , .......;

Access Structure Members


We can access structure members by using the ( . ) dot operator.
In the case where we have a pointer to the structure, we can also use the
arrow operator to access the members.
Initialize Structure Members
Structure members cannot be initialized with the declaration.
The reason for the above error is simple. When a datatype is declared, no
memory is allocated for it. Memory is allocated only when variables are
created.

1. Initialization using Assignment Operator

struct structure_name str;


str.member1 = value1;
str.member2 = value2;
str.member3 = value3;
.
.
.

2. Initialization using Initializer List

struct structure_name str = { value1, value2, value3 };


struct employee e = { 1, 'A', 1.00, "abc" };

-: Program TO use structure & access its


values :-
/ Create a structure called myStructure
#include<stdio.h>
struct myStructure
{
int myNum;
char myLetter;
};

void main()
{
// Create a structure variable of myStructure called s1
struct myStructure s1;

// Assign values to members of s1


s1.myNum = 13;
s1.myLetter = 'B';

// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);

String in structure
Example
struct myStructure
{
char myString[30]; // String
};
void main()
{
struct myStructure s1;

// Assign a value to the string using the strcpy


function
strcpy(s1.myString,"Some text");

printf("My string: %s",s1.myString);

-: Program TO use structure & access its


values :-
#include<stdio.h>
Struct str1
{
int i;
char c;
float f;
} var1; // variable declaration with structure template
void main()
{
struct str1 var1 = { 1, 'A', 1.00 };
printf("%d\n”,var1.i);
printf("\n%c\n”,var1.c);
printf("\n%f\n”,var1.f);
}

Program to use 2 variable in structure.


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

struct Books
{
char title[50];
int book_id;
};
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
Book1.book_id = 649;

/* book 2 specification */
strcpy( Book2.title, "maths");
Book2.book_id = 640;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 book_id : %d\n", Book2.book_id);
}
Program of structure contain 3 car information.

#include<stdio.h>
struct Car {
char brand[50];
char model[50];
int year;
};

int main()
{
struct Car car1 = {"BMW", "X5", 1999};
struct Car car2 = {"Ford", "Mustang", 1969};
struct Car car3 = {"Toyota", "Corolla", 2011};

printf("%s %s %d\n",car1.brand,car1.model,
car1.year);
printf("%s %s %d\n",car2.brand,car2.model,
car2.year);
printf("%s %s %d\n",car3.brand,
car3.model, car3.year);

}
Program to make structure of name,id and marks of 3 students.

#include<stdio.h>
struct student
{
char name[20];
int id;
float marks;
};
int main()
{
struct student s1,s2,s3;

printf("Enter the name, id, and marks of student 1 ");


scanf("%s %d %f",s1.name,&s1.id,&s1.marks);

printf("Enter the name, id, and marks of student 2 ");


scanf("%s %d %f",s2.name,&s2.id,&s2.marks);

printf("Enter the name, id, and marks of student 3 ");


scanf("%s %d %f",s3.name,&s3.id,&s3.marks);

printf("Printing the details....\n");


printf("%s %d %f\n",s1.name,s1.id,s1.marks);
printf("%s %d %f\n",s2.name,s2.id,s2.marks);
printf("%s %d %f\n",s3.name,s3.id,s3.marks);
}
Using typedef in the structures
typedef struct str2 {
int x;
} str2;

int main()
{
// creating structure variables using new names
str2 s1 = { 314 };
printf(" %d", s1.x);
}

Example for typedefining a structure


typedef struct employee{
int eno;
char ename[30];
float sal;
} emp;

void main ()
{
emp e = {10, "ramu”, 5000};
printf("number = %d\n”, e.eno);
printf("name = %s\n”, e.ename);
printf("salary = %f\n”, e.sal);
getch ();
}
Structure Pointer in C

A structure pointer is defined as the pointer which points to the


address of the memory block that stores a structure known as
the structure pointer. The structure pointer tells the address of
a structure in memory by pointing the variable to the structure
variable.

Structure Pointer

The structure pointer points to the address of a memory block


where the Structure is being stored. Like a pointer that tells the
address of another variable of any data type (int, char, float) in
memory. And here, we use a structure pointer which tells the address
of a structure in memory by pointing pointer variable ptr to the
structure variable.

Declare a Structure Pointer

The declaration of a structure pointer is similar to the declaration of


the structure variable. So, we can declare the structure pointer and
variable inside and outside of the main() function. To declare a
pointer variable in C, we use the asterisk (*) symbol before the
variable's name.

1. struct structure_name *ptr;

We can define a pointer that points to the structure like any other
variable. Such pointers are generally called Structure Pointers. We
can access the members of the structure pointed by the structure
pointer using the ( -> ) arrow operator.
Initialization of the Structure Pointer

1. ptr = &structure_variable;

We can also initialize a Structure Pointer directly during the


declaration of a pointer.

1. struct structure_name *ptr = &structure_variable;

C program to demonstrate structure pointer


#include <stdio.h>

struct point
{
int value;
};

int main()
{

struct point s;

// Initialization of the structure pointer


struct point *ptr = &s;
printf(“%p”,ptr);
}
Accessing the Structure Member with the Help of Pointers

There are two ways to access the members of the structure with the
help of a structure pointer:
1. With the help of (*) asterisk or indirection operator and (.) dot
operator.
2. With the help of ( -> ) Arrow operator.
Program to access the structure member using structure pointer and
the dot operator

#include <stdio.h>

struct Subject
{
char sub_name[30];
int sub_id;
};

void main()
{
struct Subject sub; // declare the Subject variable
struct Subject *ptr; // create a pointer variable (*ptr)
ptr = &sub; /* ptr variable pointing to the address of the structur
e variable sub */
strcpy (sub.sub_name, " Computer Science");
sub.sub_id = 1201;

// print the details of the Subject;


printf (" Subject Name: %s\t ", (*ptr).sub_name);
printf (" \n Subject Id: %d\t ", (*ptr).sub_id);
}
// program to illustrate the structure pointer With ( -> ) Arrow
operator.
#include <stdio.h>

struct Point
{
int x, y;
};

int main()
{
struct Point str = { 1, 2 };

// ptr is a pointer to structure point


struct Point * ptr = &str;

// Accessing structure members using structure pointer


printf("%d %d", ptr->x, ptr->y);

C Program to demonstrate Structure pointer

#include <stdio.h>
Struct person
{
int age;
float weight;
};

int main( )
{
Struct person *personPtr, person1;
personPtr = &person1;

printf("Enter age: ");


scanf("%d", &personPtr->age);

printf("Enter weight: ");


scanf("%f", &personPtr->weight);

printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);

return 0;
}
Structures as Function Arguments
You can pass a structure as a function argument in the same way as
you pass any other variable or pointer.
#include <stdio.h>
#include <string.h>

struct Books
{
char title[50];
int book_id;
};

/* function declaration */
void printBook( struct Books B1);

void main( )
{

struct Books B1={"C Programming",123};

printBook( B1 );

void printBook( struct Books B1 )


{
printf( "Book title : %s\n", B1.title);
printf( "Book book_id : %d\n", B1.book_id);
}

How to pass structure members to the


function.
#include <stdio.h>
struct student {
char name[50];
int per,rno;
};

void display(int a, int b);

int main()
{
struct student s1;

printf("Enter name: ");


gets(s1.name);
printf("Enter the roll number: ");
scanf("%d",&s1.rno);
printf("Enter percentage: ");
scanf("%d", &s1.per);
display(s1.rno,s1.per);

void display(int a,int b )


{
printf("\nDisplaying information\n");
printf("Roll number: %d", a);
printf("\nPercentage: %d", b);
}

In the above code, we created a structure to hold the name, roll number, and
percentage of the student. The input from the user is stored in the structure.
A function named display() is created, which takes the roll number and the
percentage of the student as the parameter. Using the dot (.) operator, we
accessed the member of the structure and passed it to the function.

The output of the above code is as follows:


Enter name: Gourav
Enter the roll number: 42
Enter percentage: 98

Displaying information
Roll number: 42
Percentage: 98

You might also like