MCS-011 Problem Solving and Programming

First year, Semester 1

Chapters

Newsletter

Difference between Structures and Arrays

Structures and arrays are both used to group multiple pieces of data, but they serve different purposes and have distinct characteristics. Here’s a detailed comparison with examples:

Definitions

  1. Array: A collection of elements of the same data type stored in contiguous memory locations.
  2. Structure: A user-defined data type in C/C++ that groups variables of different data types under a single name.


Differences


ArraysStructure
Data Type Consistency
All elements must be of the same type.
Members can be of different types.
Memory Layout
Elements are stored in contiguous memory locations.
Members may not be stored contiguously due to padding for alignment.
Accessing Elements
Access elements using an index.
Access members using the dot operator (.).
Usage
Suitable for lists of similar items (e.g., a list of integers).
Suitable for grouping related but different items (e.g., a person's information).
Example
#include <stdio.h>
int main() { // Define an array of integers int numbers[5] = {1, 2, 3, 4, 5}; // Access and print array elements for(int i = 0; i < 5; i++) { printf("Element %d: %d\n", i, numbers[i]); } return 0; }
#include <stdio.h> #include <string.h> // Define a structure for a Person struct Person { char name[50]; int age; float height; }; int main() { // Declare and initialize a structure variable struct Person person1; strcpy(person1.name, "John Doe"); person1.age = 30; person1.height = 5.9; // Access and print structure members printf("Name: %s\n", person1.name); printf("Age: %d\n", person1.age); printf("Height: %.1f\n", person1.height); return 0; }


Report an issue

Reporting: Difference between Structures and Arrays (topic)

Related Posts