0% found this document useful (0 votes)
14 views7 pages

Arrays and Structures in C Programming

The document provides a comprehensive overview of arrays and structures in C programming, detailing the definitions, types, and initialization methods for one-dimensional and two-dimensional arrays. It also explains the concept of structures and unions, including their syntax, declaration, and differences in memory allocation. Additionally, it highlights the advantages and limitations of arrays, as well as the memory representation of both arrays and structures.

Uploaded by

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

Arrays and Structures in C Programming

The document provides a comprehensive overview of arrays and structures in C programming, detailing the definitions, types, and initialization methods for one-dimensional and two-dimensional arrays. It also explains the concept of structures and unions, including their syntax, declaration, and differences in memory allocation. Additionally, it highlights the advantages and limitations of arrays, as well as the memory representation of both arrays and structures.

Uploaded by

priyanka.g.d987
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

​Unit-3:​​Arrays & Structures​

​ efinition​​:​​An array is a​​fixed sized,​​sequenced​​collection of elements of the​​same​


D
​data type.​​An array can be used to represent a​​list​​of numbers, or a list of names.​
​Types of arrays​
​●​ ​One-dimensional array​
​●​ ​Two-dimensional array​

​One-dimensional array:​

​ ​ ​one-dimensional​ ​array​ ​is​ ​a​ ​linear​ ​collection​ ​of​ ​elements​ ​of​ ​the​ ​same​ ​data​ ​type​
A
​stored in contiguous memory locations.​

​Given one variable name using only one subscript​

​Example: float height[50];​

​int number[5];​

​Declaration of one-dimensional array:​

​Syntax​​for array declaration: type variable_name [size];​

​Ex: int marks[10]; // declares an array of 10 integers​

​Initialization of one-dimensional array:​

​ ssigning​ ​the​ ​required​ ​information​ ​to​ ​a​ ​variable​ ​before​ ​processing​ ​is​ ​called​
A
​initialization​

​An array can be initialized at either of the following two stages:​

​​ A
● ​ t compile time​
​●​ ​At run time​

​Compile-time initialization:​

​array is initialized when they are declared.​

​syntax​​:​ ​type name [size]= {values};​

​Examples:​ ​int num[3]={2,5,6};​

​int a[3]={10,20,30,40}; //error.​

​int a[6]={10,15};​

I​ f​​fewer​​values​​are​​provided,​​the​​remaining​​elements​​are​​automatically​​initialized​​to​
​zero.​

​Run time initialization:​

I​ t​ ​refers​ ​to​ ​assigning​ ​values​ ​to​ ​variables​ ​or​​arrays​​while​​the​​program​​is​​executing​​,​


​rather than at the time of declaration.​
​ xample program:​
E
#include <stdio.h>​

void main()​

{​

int n, i;​

int arr[n];
​ // array size decided at run time​
printf("Enter number of elements: ");​

scanf("%d", &n);​

​rintf("Enter %d elements:\n", n);​


p
for(i = 0; i < n; i++)​

{​

scanf("%d", &arr[i]);
​ // run time initialization​
}​

printf("You entered:\n");​

for(i = 0; i < n; i++) {​

printf("%d ", arr[i]);​

}​

}​

​Difference from Compile-Time Initialization​


​Aspect​ ​Compile-Time Initialization​ ​Run-Time Initialization​

​When values are​ ​At declaration (before execution)​ ​During program execution​
​assigned​

​Example​ ​int arr[3] = {10, 20, 30};​ ​Values entered via scanf()​

​Flexibility​ ​Fixed, cannot change without​ ​Flexible, depends on user input​


​editing code​ ​or logic​

​ emory representation of array:​


M
​Arrays​ ​are​ ​stored​ ​in​ ​contiguous​ ​memory​ ​blocks,​ ​meaning​ ​each​ ​element​ ​is​ ​placed​
​right next to the previous one in memory.​
​int a[5] = {4, 5, 33, 13, 1};​

​Index​ ​Value​ ​Memory Address (hypothetical)​

​a[0]​ ​4​ ​1000​

​a[1]​ ​5​ ​1004​

​a[2]​ ​33​ ​1008​

​a[3]​ ​13​ ​1012​

​a[4]​ ​1​ ​1016​


​Address(array[i]) = Base_Address + (i * size_of_each_element)​
​Ex: Address(a[3]) = 1000 + (3 * 4)​
​=1012​
​ wo-dimensional array​
T
​A two-dimensional array can be defined as an array of arrays.​
​The 2D array is organized as matrices which can be represented as the collection of​
​rows and columns.​
​Declaration​​:​
​Syntax​​: data_type array_name [rows][columns];​
​Example:​ ​int a[3][4];​
​Initialization of Two-dimensional arrays​
​Syntax​​of initializing two dimensional arrays:​
​type array_name[row_size][column_size]={list of values};​
​Example​​:​
​int mat[2][3]={2,2,2,3,3,3};​
​the above statement can be written as​
​int mat[2][3]={{2,2,2},{3,3,3}};​
​Rows/columns index​ ​0​ ​1​ ​2​

​0​ ​2​ ​2​ ​2​


​1​ ​3​ ​3​ ​3​
​ emory Representation:​
M
​In C, 2D arrays are stored in row-major order—meaning all elements of the first row​
​are stored first, followed by the second row, and so on.​
​int matrix[2][3] = {​
​{1, 2, 3},​
​{4, 5, 6}​
​};​

​Row​ ​Column​ ​Value​ ​Memory Address (hypothetical)​

​0​ ​0​ ​1​ ​1000​

​0​ ​1​ ​2​ ​1004​

​0​ ​2​ ​3​ ​1008​

​1​ ​0​ ​4​ ​1012​

​1​ ​1​ ​5​ ​1016​

​1​ ​2​ ​6​ ​1020​


​Total memory = rows × columns × size of data type.​
​Advantages of arrays​

​​ E
● ​ fficient for storing and accessing a collection of data of the same type.​
​●​ ​Useful for problems like storing student marks, processing lists, or​
​performing mathematical computations.​

​Limitations of arrays​

​​ F
● ​ ixed size (cannot grow dynamically).​
​●​ ​All elements must be of the same data type.​
​●​ ​Insertion and deletion operations are less flexible compared to linked lists.​

​Structures​
​ structure in C is a user-defined data type that allows grouping variables of​
A
​different data types under a single name.​

​Structures are defined using the struct keyword.​

​Syntax:​

​struct structure_name​

​{​

​data_type member_variable1;​

​data_type member_variable2;​

​……​

​};​

​Ex:​ struct​​
​ student​

{​

char name[20];​

int roll_no;​

float marks;​

char gender;​

long int phone_no;​


};​

​Declaring structure variable:​

​ e can declare a variable for the structure so that we can access the member of the​
W
​structure easily.​
​There are two ways to declare structure variable:​

​1.​ B
​ y struct keyword within main() function​
​Ex:​ struct student​

{​

char name[20];​

int roll_no;​

float marks;​

char gender;​

long int phone_no;​

};​

void main()​

{​

struct student s1, s2;​

}​

​2.​ ​By declaring a variable at the time of defining the structure.​


​Ex:​ ​truct student​
s
{​

char name[20];​

int roll_no;​

float percentage;​

char gender;​

long int phone_no;​

}s1,s2;​

​Initialization:​

​There are multiple ways to initialize structure members:​

​●​ ​Using Dot Operator​​:​​ [Link]= "Asha";​


s1.roll_no = 10201;​

[Link] = 92.8;​

​●​ ​Value Initialization​​:​ ​struct​​student s2 = {"Ravi", 10202, 93.5};​
​●​ ​Named Member Initialization (C99 onwards):​

​struct​​student s3 = {.name = "Meena", .id = 10203, .percentage = 98.9};​

​Order matters in value initialization unless using named members​

​ ccessing structure members:​


A
​There are two ways to access structure members:​
​●​ ​By dot operator(.)​

​Ex:​ #include<stdio.h>​

​truct​​
s student​
{​

char name[10];​

int rollNo;​

float marks;​

}s1;​

​oid main()​
v
{​

printf("Name: %s", [Link]);​

printf("Roll No: %d", [Link]);​

printf("marks: %.2f", [Link]);​

}​

​●​ ​By arrow operator(🡪)​

​Ex:​​include<stdio.h>​
#
struct​​
​ student​
{​

char name[10];​

int rollNo;​

float marks;​

}s1;​

void main()​

{​

struct student *ptr;​

ptr = &s1;​

​rintf("Roll No: %d\n", ptr->rollNo);​


p
printf("Name: %s\n", ptr->name);​

printf("Marks: %.2f\n", ptr->marks);​

}​

​Unions​
​ efinition:​​A union is a user-defined data type in C, similar to a structure, but with a key​
D
​difference:​
​●​ ​All members share the same memory location.​
​●​ ​This means only one member can hold a value at a time.​

​Defining union:​
​Syntax​​:​ ​ nion​​union_name​
u
​{​
​data_type member1;​
​data_type member2;​
​.​
​.​
​data_type memeberN;​
​};​
​Ex:​ union employee​

{​

int id;​

char name[50];​

float salary;​

};​

​Declaration:​​Like structure declaration,​​unions are declared before they are used in a​
​C program. They can be declared in two styles.​
​1.​ w​ ithin the union definition:​
​Example​​ :​ ​ union number​
{​
​ int nl;​

float n2;​

}x;​

​2.​ o​ utside the union definition​


​Example:​
union number​

{​
​ int nl;​

float n2;​

};​

union number x;​

​Initialization:​

​.n1 = 10;​
x
x.n2= 3.14;
​ // Overwrites the value of x.n1​

​ nly the last assigned member holds a valid value. Previous values are overwritten​
O
​due to shared memory.​

​ emory Representation:​
M
​The size of a union is equal to the size of its largest member.​
​Example​​: If rollNo (4 bytes), name[30] (30 bytes), and marks (4 bytes) are members,​
​the union size will be 30 bytes (largest member).​

​Difference between Structures and Unions:​

​Feature​ ​Structure​ ​Union​

​Keyword​ ​struct​ ​union​

​ emory​
M ​Separate memory for each​
​Shared memory for all members​
​Allocation​ ​member​

​Size​ ​Sum of all member sizes​ ​Size of the largest member​

​All members can hold values​ ​Only one member holds a valid value at a​
​Data Access​
​simultaneously​ ​time​

​When all data fields are needed​


​Use Case​ ​When only one field is needed at a time​
​together​

Common questions

Powered by AI

Structures in C programming permit grouping of variables of different data types under a single name, thereby enabling the handling of diverse data in a unified manner . This capability allows complex data types to be managed efficiently without losing the simplicity of basic data types. Typical use cases include modeling real-world entities like student records, where each record might hold a mix of int, char, and float for storing attributes like ID, name, and grades. This facilitates the organization and manipulation of heterogeneous data logically connected, providing a base for more complex data management .

Unions can be more advantageous than structures in memory-sensitive applications due to their method of allocating shared memory for the largest member only, thereby conserving space when only one member value is needed at a time . In contrast, structures allocate separate memory for each member, which can be less efficient for memory usage as it sums up all member sizes. This makes unions an economical choice when simultaneously holding data for multiple fields is not needed, as in scenarios where different types of data are processed sequentially rather than concurrently . Techniques such as discriminant keys or type specifiers are sometimes employed to manage the use of unions safely by indicating which member currently holds a valid value.

The dot operator (.) is used to access structure members from a structure variable directly, requiring the structure variable (or an instance) to access its members. For example: struct student s1; s1.roll_no = 102; . The arrow operator (->), on the other hand, is used to access members when you have a pointer to a structure. It dereferences the pointer to access members. Example: struct student *ptr; ptr = &s1; ptr->roll_no = 102; . The dot operator is used for regular structure variables, while the arrow operator is for pointers to structures.

One-dimensional arrays are linear collections of elements stored in contiguous memory locations, where each element is accessed using a single subscript index . Two-dimensional arrays, however, are arrays of arrays and are typically represented as matrices. They are stored in row-major order, meaning that all elements of the first row are stored first, followed by the second row, and so on. In memory, if we initialize a 2D array like int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}, the elements are stored in the sequence 1, 2, 3, 4, 5, 6 in contiguous memory slots . Initialization for one-dimensional arrays can happen at compile time with syntax like int arr[3] = {1, 2, 3}; or at run time by reading input during program execution. Meanwhile, two-dimensional arrays are initialized using syntax like int mat[2][3]={2,2,2,3,3,3}; where braces separate rows .

In structures, memory is allocated separately for each member. This means the size of a structure is the sum of all its members' sizes, allowing all members to hold values simultaneously . Conversely, in unions, all members share the same memory location, so the size of a union is determined by its largest member. Only one member can hold a value at a time, with the most recent assignment overwriting previous values of other members . This has significant implications: structures are suited for cases where you need to use multiple fields at once, while unions are appropriate when only one field is needed at any given time, optimizing memory usage .

Run-time initialization of arrays is more beneficial when flexibility is required, as it allows the program to determine the size and initialize array elements during execution based on user input or other runtime data. This contrasts with compile-time initialization, which fixes the array size and initializes values during compilation. Scenarios such as dynamic data processing, where user input determines the number of elements, benefit from run-time initialization, as it allows adjusting the array's length and content, whereas compile-time is more rigid and requires code modification for change .

The memory required for a two-dimensional array is calculated by multiplying the number of rows by the number of columns and then by the size of the data type of the array elements. For example, if we have an int data type array int matrix[3][4], assuming int takes 4 bytes, the total memory allocation would be 3 rows * 4 columns * 4 bytes = 48 bytes. This approach involves storing elements from each row sequentially in a row-major order, where each row is stored contiguously in memory followed by the next .

In C, structure members can be initialized using dot operator assignment after declaration, direct value initialization, or named member initialization. Named member initialization (available from C99 onwards) allows specifying only the members we want to initialize, in any order, using the syntax struct student s3 = {.name = "Meena", .rollNo = 10203, .marks = 98.9} . This method offers the advantage of clearer code, as members are explicitly named, reducing errors associated with changes in structure order, enhancing code readability, and ensuring only specific fields are modified, unlike traditional ordered initialization which must match declaration order .

During compile-time initialization, when fewer initial values are provided than the array size, the remaining elements are automatically initialized to zero, which prevents undefined behavior from accessing uninitialized memory locations . This feature ensures that all elements have a known value, avoiding garbage data. However, inadvertent or mistaken expectations about default values could arise if a developer assumes intentional initialization for all elements, potentially leading to logical errors if not all elements are explicitly set and utilized without checks .

Arrays are efficient for storing and accessing collections of data of the same type because of their contiguous memory allocation, which allows rapid data retrieval via indexing . However, they have fixed sizes, making them inflexible if the dataset size varies after allocation . Arrays also require all elements to be of the same type and are less flexible for insertion and deletion compared to linked lists, where elements can be easily added or removed without reallocation. Linked lists offer dynamic resizing and easier management for such operations, albeit with higher overhead due to pointer storage and non-contiguous memory, making access time slower compared to arrays .

You might also like