0% found this document useful (0 votes)
11 views16 pages

Structures

This document provides an overview of structures in C, explaining their definition, declaration, initialization, and how to access their members. It covers examples of creating and manipulating structures, including dynamic memory allocation and string copying within structures. Additionally, it discusses user-defined data types, passing structures as function arguments, and using pointers with structures.

Uploaded by

sathwikakantekar
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)
11 views16 pages

Structures

This document provides an overview of structures in C, explaining their definition, declaration, initialization, and how to access their members. It covers examples of creating and manipulating structures, including dynamic memory allocation and string copying within structures. Additionally, it discusses user-defined data types, passing structures as function arguments, and using pointers with structures.

Uploaded by

sathwikakantekar
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

UNIT-1

Structures:

A structure in C is a derived or user-defined data type. We use the keyword


struct to define a custom data type that groups together the elements of
different types. The difference between an array and a structure is that an
array is a homogenous collection of similar types, whereas a structure can
have elements of different types stored adjacently and identified by a name.

We are often required to work with values of different data types having
certain relationships among them. For example, a book is described by its
title (string), author (string), price (double), number of pages (integer),
etc. Instead of using four different variables, these values can be stored in a
single struct variable.

Declare (Create) a Structure

You can create (declare) a structure by using the "struct" keyword followed
by the structure_tag (structure name) and declare all of the members of the
structure inside the curly braces along with their data types.

To define a structure, you must use the struct statement. The struct
statement defines a new data type, with more than one member.

Syntax of Structure Declaration

The format (syntax) to declare a structure is as follows −

struct [structure tag]


{
member definition;
member definition;
... member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal
variable definition, such as "int i;" or "float f;" or any other valid variable
definition.

At the end of the structure's definition, before the final semicolon, you can
specify one or more structure variables but it is optional.

Example

In the following example we are declaring a structure for Book to store the
details of a Book −

struct book
{
char title[50];
char author[50];
double price;
int pages;
} book1;

Here, we declared the structure variable book1 at the end of the structure
definition. However, you can do it separately in a different statement.

Structure Variable Declaration

To access and manipulate the members of the structure, you need to declare
its variable first. To declare a structure variable, write the structure name
along with the "struct" keyword followed by the name of the structure
variable. This structure variable will be used to access and manipulate the
structure members.

Example

The following statement demonstrates how to declare (create) a structure


variable

struct book book1;


Usually, a structure is declared before the first function is defined in the
program, after the include statements. That way, the derived type can be
used for declaring its variable inside any function.

Structure Initialization

The initialization of a struct variable is done by placing the value of each


element inside curly brackets.

Example

The following statement demonstrates the initialization of structure

struct book book1= {"Learn C", "Dennis Ritchie",


675.50,325};

Accessing the Structure Members

To access the members of a structure, first, you need to declare a structure


variable and then use the dot (.) operator along with the structure
variable.

Example 1

The four elements of the struct variable book1 are accessed with the dot (.)
operator. Hence, "[Link]" refers to the title element, "[Link]" is
the author name, "[Link]" is the price, "[Link]" is the fourth
element (number of pages).
Take a look at the following example −

#include <stdio.h>
struct book
{
char title[10];
char author[20];
double price;
int pages;
};

int main()
{
struct book book1 = {"Learn C", "Dennis
Ritchie", 675.50, 325}; printf("Title: %s \n",
[Link]);
printf("Author: %s \n", [Link]);
printf("Price: %lf\n", [Link]);
printf("Pages: %d \n", [Link]);
printf("Size of book struct: %d", sizeof(struct
book));
return 0;
}

Output
Run the code and check its output −

Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Size of book struct: 48
Example 2

In the above program, we will make a small modification. Here, we will put
the type definition and the variable declaration together, like this −

struct book{
char title[10];
char author[20];
double price;
int pages;
} book1;

Note that if you a declare a struct variable in this way, then you cannot
initialize it with curly brackets. Instead, the elements need to be assigned
individually.

#include <stdio.h>
#include <string.h>
struct book
{
char title[10];
char author[20];
double price;
int pages;
} book1;

int main()
{
strcpy([Link], "Learn C");
strcpy([Link], "Dennis Ritchie");
[Link] = 675.50;
[Link] = 325;
printf("Title: %s \n", [Link]);
printf("Author: %s \n", [Link]);
printf("Price: %lf \n", [Link]);
printf("Pages: %d \n", [Link]);
return 0;
}

Output
When you execute this code, it will produce the following output −

Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325

Copying Structures

The assignment (=) operator can be used to copy a structure directly. You
can also use the assignment operator (=) to assign the value of the member
of one structure to another.

Let's have two struct book variables, book1 and book2. The variable book1
is initialized with declaration, and we wish to assign the same values of its
elements to that of book2.

We can assign individual elements as follows −

struct book book1 = {"Learn C", "Dennis Ritchie",


675.50, 325}, book2;
strcpy([Link], [Link]);
strcpy([Link], [Link]);
[Link] = [Link];
[Link] = [Link];

Note the use of strcpy() function to assign the value to a string variable
instead of using the "= operator".
Example

You can also assign book1 to book2 so that all the elements of book1 are
respectively assigned to the elements of book2. Take a look at the following
program code −

#include <stdio.h>
#include <string.h>
struct book
{
char title[10];
char author[20];
double price;
int pages;
};

int main()
{
struct book book1 = {"Learn C", "Dennis Ritchie",
675.50, 325}, book2;
book2 = book1;
printf("Title: %s \n", [Link]);
printf("Author: %s \n", [Link]);
printf("Price: %lf \n", [Link]);
printf("Pages: %d \n", [Link]);
printf("Size of book struct: %d", sizeof(struct
book));
return 0;
}

Output
Run the code and check its output −

Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Size of book struct: 48
Demonstrate the Dynamic Memory Allocation for Structure

This program asks the user to store the value of noOfRecords and allocates the
memory for the noOfRecords structure variables dynamically using the malloc()
function.

#include <stdio.h>

#include <stdlib.h>

struct course

int marks;

char subject[30];

};

int main()

struct course *ptr;

int noOfRecords;

printf("Enter the number of records: "); scanf("%d", &noOfRecords);

// Memory allocation for noOfRecords structures

ptr = (struct course *)malloc(noOfRecords * sizeof(struct course));

for (int i = 0; i < noOfRecords; ++i)

{
printf("Enter subject and marks:\n"); scanf("%s %d", (ptr + i)-
>subject, &(ptr + i)->marks);

printf("Displaying Information:\n");

for (int i = 0; i < noOfRecords; ++i)

printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);

free(ptr);

return 0;}

STRING COPY IN STRUCTURES

"String copy in structures" refers to the process of copying a string value from
one source to a string member within a structure, typically using the strcpy
function in C/C++ to perform the copy operation, ensuring that the destination
string within the structure has enough allocated memory to hold the copied
string.

Key points about string copy in structures:

Accessing the string member:

To copy a string into a structure, you need to access the specific string member within
the structure using the structure variable and the member name, then use strcpy to
copy the string value to that member.

strcpy function:
This standard C library function takes two arguments: the destination string (the
structure member) and the source string to be copied.

Memory management:

Ensure sufficient size: Before copying, make sure the character array within your
structure member is large enough to accommodate the entire source string, including
the null terminator.

Potential buffer overflow: Using strcpy without proper size checks can lead to buffer
overflows if the source string is longer than the allocated space in the structure member.

#include <stdio.h>

#include <string.h>

struct Person {

char name[50];

int age;

};

int main() {

struct Person person;

// Copy "John Doe" to the 'name' member of the 'person' structure

strcpy([Link], "John Doe");

printf("Person's name: %s\n", [Link]);

return 0;

}
Important considerations:

String literal limitations:

Do not directly copy string literals to a structure member using strcpy as string literals
are usually stored in read-only memory.

Alternative methods:

Manual copying loop: For finer control, you can write a loop to copy characters one by
one.

strncpy: This function provides a way to limit the number of characters copied,
preventing potential buffer overflows.

String class (C++): In C++, consider using the std::string class which handles
memory management more robustly.

User-defined Data Types (typedef),

#include <stdio.h>

typedef struct complex {

float real;

float imag;

} complex;
complex add(complex n1, complex n2);

int main() {

complex n1, n2, result;

printf("For 1st complex number \n");

printf("Enter the real and imaginary parts: ");

scanf("%f %f", &[Link], &[Link]);

printf("\nFor 2nd complex number \n");

printf("Enter the real and imaginary parts: ");

scanf("%f %f", &[Link], &[Link]);

result = add(n1, n2);

printf("Sum = %.1f + %.1fi", [Link], [Link]);

return 0;

complex add(complex n1, complex n2) {

complex temp;

[Link] = [Link] + [Link];

[Link] = [Link] + [Link];

return (temp);
}

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.

Example

Take a look at the following program code. It demonstrates how you can
pass a structure as a function argument −

#include <stdio.h>

#include <string.h>

struct Books

char title[50];

char author[50];

char subject[100];

int book_id;

};

/* function declaration */

void printBook(struct Books book);

int main()

struct Books Book1; /* Declare Book1 of type Book */

struct Books Book2; /* Declare Book2 of type Book */


/* book 1 specification */

strcpy([Link], "C Programming");

strcpy([Link], "Nuha Ali");

strcpy([Link], "C Programming Tutorial");

Book1.book_id = 6495407;

/* book 2 specification */

strcpy([Link], "Telecom Billing");

strcpy([Link], "Zara Ali");

strcpy([Link], "Telecom Billing Tutorial");

Book2.book_id = 6495700;

/* print Book1 info */

printBook(Book1);

/* Print Book2 info */

printBook(Book2);

return 0;

void printBook(struct Books book)

printf("Book title : %s\n", [Link]);

printf("Book author : %s\n", [Link]);

printf("Book subject : %s\n", [Link]);

printf("Book book_id : %d\n", book.book_id);

}
Output
When the above code is compiled and executed, it produces the following
result −

Book title : C Programming


Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

Structures and pointers

You can define pointers to structures in the same way as you define pointers
to any other variable.

Declaration of Pointer to a Structure

You can declare a pointer to a structure (or structure pointer) as follows −

struct Books *struct_pointer;


Initialization of Pointer to a Structure

You can store the address of a structure variable in the above pointer
variable struct_pointer. To find the address of a structure variable, place
the '&' operator before the structure's name as follows −

struct_pointer = & book1;

You might also like