Module-3
Arrays and Strings
School of Electronics Engineering (SENSE)
Vellore Institute of Technology
Chennai
(School of Electronics Engineering (SENSE)Vellore Institute
Module-3of Arrays
Technology
and Strings
Chennai) 1 / 50
Module 3: Arrays and Strings
Outline
1 Introduction to Arrays
2 One-Dimensional Arrays, Multi-Dimensional Arrays
3 Arrays in Memory, Operations on Arrays
4 Introduction to Strings
5 String Manipulations
6 Functions in C
7 Function Parameters and Return Types
8 Recursion in Functions
9 Introduction to Pointers
10 Pointer Arithmetic
11 Pointers and Arrays, Strings, Functions
12 Introduction to Structures
13 Accessing Structure Members
14 Structures and Functions
15 Introduction to Unions
16 Structures vs Unions
Module-3 Arrays and Strings 2/50
Introduction to Arrays
Definition
An array is a collection of items stored at contiguous memory locations.
In C, arrays are used to store similar types of elements.
Application in Embedded Systems
Arrays are used in embedded systems for handling multiple similar data
efficiently, such as sensor readings, buffer storage, and lookup tables.
Module-3 Arrays and Strings 3/50
One-Dimensional Arrays
Syntax and Declaration
int arr[10]; // Declares an array of 10 integers
Example
arr[0] = 1; // Sets the first element to 1
Module-3 Arrays and Strings 4/50
Declaration of One-Dimensional Arrays
Array Declaration Syntax
type arrayName[arraySize];
Example: Sensor Readings Array
#define NUM_SENSORS 4
int sensorReadings[NUM_SENSORS]; //Array for storing sensor va
Note on Embedded Systems
In embedded C, the size of arrays is often determined by the number of
physical components, like sensors or actuators, connected to the
microcontroller.
Module-3 Arrays and Strings 5/50
Initializing One-Dimensional Arrays
Array Initialization Syntax
type arrayName[arraySize] = {val1, val2, ..., valN};
Example: Setting Initial Sensor States
int sensorStates[NUM_SENSORS] = {0}; // Initialize all to 0
Embedded Systems Context
Initialization is crucial in embedded systems to ensure that memory has
defined values before use, particularly for registers or state variables.
Module-3 Arrays and Strings 6/50
Accessing Array Elements
Accessing Elements Syntax
Elements in an array are accessed using their index.
arrayName[index]
Example: Accessing an Element
int array[5] = {1, 2, 3, 4, 5};
int firstElement = array[0]; // Access first element
Embedded Systems Consideration
When accessing array elements in embedded systems, ensure that the
index is within the bounds to prevent undefined behavior and potential
system crashes.
Module-3 Arrays and Strings 7/50
Iterating Over Arrays
Iterating Over Arrays
To perform operations on each element in an array, a loop is used.
for (int i = 0; i < arraySize; i++) {
// Code to execute
}
Example: Summing Array Elements
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += array[i];
}
Embedded Systems Tip
In time-critical embedded applications, consider the loop’s impact on
execution time and optimize the iteration process.
Module-3 Arrays and Strings 8/50
Example: Summing Elements in an Array
Standard C Example
int main() {
int values[5] = {5, 10, 15, 20, 25};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += values[i];
}
printf("Sum of values: %d\n", sum);
return 0;
}
Module-3 Arrays and Strings 9/50
Multi-Dimensional Arrays Overview
Definition
Multi-dimensional arrays are arrays of arrays.
They are used to represent data in more than one dimension, such as
matrices.
Module-3 Arrays and Strings 10/50
Multi-Dimensional Arrays
Syntax and Declaration
int multiArr[3][4]; // Declares a 3x4 array
Example
multiArr[0][1] = 5; // Element at row 0, column 1 to 5
Module-3 Arrays and Strings 11/50
Declaration of Multi-Dimensional Arrays
Declaration Syntax
type arrayName[size1][size2];
Example: 2D Array for LED Matrix
#define ROWS 3
#define COLS 3
int ledMatrix[ROWS][COLS]; // LED states for a 3x3 matrix
Embedded C Context
Such arrays can represent physical layouts in hardware, like an LED matrix,
with each element controlling the state of an LED.
Module-3 Arrays and Strings 12/50
Initializing Multi-Dimensional Arrays
Initialization Syntax
type arrayName[size1][size2] = {{val1, val2}, {...}};
Standard C Example
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
Embedded C Application
Initializing state matrices for devices like displays where each element
represents a pixel or segment state.
Module-3 Arrays and Strings 13/50
Accessing Multi-Dimensional Array Elements
Accessing Elements
Use row and column indices to access elements in a multi-dimensional
array.
arrayName[row][column]
Standard C Example
int value = matrix[1][2]; // Accesses the element at second ro
Embedded C Context
For embedded systems, ensure the indices are within bounds to maintain
system stability.
Module-3 Arrays and Strings 14/50
Nested Loops and Multi-Dimensional Arrays
Using Nested Loops
Nested loops allow iteration over rows and columns of a multi-dimensional array.
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
// Access array elements
}
}
Standard C Example
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
Embedded C Consideration
In embedded systems, nested loops are commonly used for scanning or controlling a grid of
sensors or actuators.
Module-3 Arrays and Strings 15/50
Example: Matrix Addition
Standard C Example - Adding Two Matrices
void addMatrices(int A[2][3], int B[2][3], int C[2][3]) {
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 3; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
}
Embedded C Application
Matrix addition can be used in embedded systems for combining data from
multiple sensor arrays.
Module-3 Arrays and Strings 16/50
Arrays in Memory: How C Stores Arrays
Memory Layout of Arrays
Discuss how arrays are contiguous blocks of memory and how
multi-dimensional arrays are stored in row-major order.
Embedded C Significance
Understanding memory layout is crucial in embedded systems for
optimizing data storage and access patterns.
Module-3 Arrays and Strings 17/50
Address Arithmetic in Arrays
Understanding Address Arithmetic
Addresses of array elements are calculated using the base address and
the size of the element type.
This is essential for pointer arithmetic and understanding how arrays
are accessed in memory.
Standard C Example
int array[5];
int *ptr = array;
printf("%p %p", ptr, ptr + 1); // Prints contiguous addresses
Embedded C Application
Directly manipulating memory addresses is common in embedded systems,
for instance when interfacing with hardware registers.
Module-3 Arrays and Strings 18/50
Example: Searching an Array
Implementing a Search Algorithm
A linear search algorithm iterates over an array to find a value.
This is a straightforward example of how to traverse an array with a
loop.
Standard C Code for Linear Search
int linearSearch(int arr[], int size, int value) {
for (int i = 0; i < size; i++) {
if (arr[i] == value) return i;
}
return -1; // Value not found
}
Embedded C Scenario
Searching through a data array to find a sensor reading that exceeds a
threshold could trigger an event or alert.
Module-3 Arrays and Strings 19/50
Strings in C: A Special Kind of Array
What Are Strings in C?
In C, strings are arrays of characters terminated by a null character \0.
Usage in Embedded Systems
Strings are often used for storing data read from or to be written to
peripherals, like displays in embedded systems.
Module-3 Arrays and Strings 20/50
Declaring and Initializing Strings
Declaration and Initialization
char str[] = "Hello, World!";
Embedded C Example
char errorMessage[20] = "Error Code: ";
Note
String initialization automatically includes the null terminator.
Module-3 Arrays and Strings 21/50
Reading and Writing Strings
Using Standard I/O Functions
scanf("%s", str);
printf("%s", str);
Embedded C Considerations
In embedded systems, functions like ‘sprintf‘ and ‘sscanf‘ are used for
formatting strings to interact with hardware or protocol messages.
Module-3 Arrays and Strings 22/50
String Manipulation Functions
Common Functions
‘strlen‘ - Get string length
‘strcpy‘ - Copy string
‘strcat‘ - Concatenate strings
‘strcmp‘ - Compare two strings
Embedded Systems Note
Use these functions carefully to avoid buffer overflows, which are critical in
the context of embedded systems with limited memory.
Module-3 Arrays and Strings 23/50
Example: String Concatenation
Concatenating Two Strings
char greeting[50] = "Hello, ";
char name[] = "John";
strcat(greeting, name);
Embedded C Application
String concatenation might be used in embedded systems for creating log
messages or protocol frames.
Module-3 Arrays and Strings 24/50
Functions in C
Definition and Purpose
Functions are reusable blocks of code that perform a specific task. They
help modularize the code, making it more readable and maintainable.
Embedded Systems Context
Functions in embedded systems are used to encapsulate hardware control
operations, algorithms, and routines.
Module-3 Arrays and Strings 25/50
Declaring and Defining Functions
Function Declaration (Prototype)
void functionName(parameters);
Function Definition
void functionName(parameters) {
// Code to execute
}
Note
Function prototypes are often declared in header files, while definitions are
in source files.
Module-3 Arrays and Strings 26/50
Declaring and Defining Functions
Figure: Function Declaration
Module-3 Arrays and Strings 27/50
Calling Functions in C
Calling a Function
functionName(arguments);
Example
void turnOnLED(int ledNumber);
turnOnLED(1); // Turns on LED number 1
Embedded C Tip
Ensure that any functions that interface with hardware are called with the
correct timing and context to avoid system errors.
Module-3 Arrays and Strings 28/50
Calling Functions in C
Module-3 Arrays and Strings 29/50
Passing Parameters to Functions
Parameter Passing
In C, parameters can be passed by value, where a copy of the data is
made, or by reference, using pointers, which allows the function to modify
the original data.
Pass by Value Example
void setTemperature(int temp);
Pass by Reference Example
void resetCounter(int *counter) {
*counter = 0;
}
Module-3 Arrays and Strings 30/50
The Return Statement and Return Types
Returning Values from Functions
Functions in C can return a value. The type of the return value must
match the function’s return type.
Return Statement Example
int getSensorData() {
return sensorValue; // Assume sensorValue is an int
}
Embedded C Application
Functions that interact with hardware components often return status
codes, data readings, or boolean values indicating success or failure.
Module-3 Arrays and Strings 31/50
Example: A Function to Find Maximum Value
Function to Determine the Maximum of Two Integers
int max(int num1, int num2) {
return (num1 > num2) ? num1 : num2;
}
Calling the Function
int a = 5, b = 10;
int maximum = max(a, b);
printf("Maximum: %d", maximum);
Embedded C Usage
Such a function could be used in an embedded system to determine the
highest sensor value, control signal, or other measurement critical to the
system’s operation.
Module-3 Arrays and Strings 32/50
The Stack and Functions: How C Handles Calls
Understanding the Stack
Each function call in C is managed using a stack data structure that stores
parameters, local variables, and return addresses.
Embedded C Consideration
Stack size is limited in embedded systems. Recursive functions or deep
function calls can lead to stack overflow.
Module-3 Arrays and Strings 33/50
Recursion in Functions: Basics
What is Recursion?
Recursion occurs when a function calls itself to solve a problem by
breaking it down into smaller, more manageable sub-problems.
Example: Recursive Function for Factorial
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
Embedded C Note
Recursive functions should be used with caution in embedded systems due
to limited stack space.
Module-3 Arrays and Strings 34/50
Example: Recursive Factorial Function
Full Recursive Factorial Program in C
#include <stdio.h>
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
int num = 5;
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}
Module-3 Arrays and Strings 35/50
Recursion vs. Iteration: Comparative Study
Comparing Recursion and Iteration
Recursion can be more intuitive and easier to write for problems that
naturally fit the recursive pattern.
Iteration is generally more memory-efficient and can be faster because
it does not incur the overhead of multiple function calls.
Embedded Systems Best Practice
Prefer iteration over recursion when working with resource-constrained
embedded systems, unless recursion significantly simplifies the problem.
Module-3 Arrays and Strings 36/50
Introduction to Pointers
What is a Pointer?
A pointer is a variable that stores the memory address of another variable.
Pointers are a powerful feature in C that allow for dynamic memory
management and efficient array handling.
Importance in Embedded Systems
Pointers are critical in embedded systems for interacting with hardware,
managing memory, and optimizing performance.
Module-3 Arrays and Strings 37/50
Declaring and Using Pointers
Module-3 Arrays and Strings 38/50
Declaring and Using Pointers
Pointer Declaration
type *pointerName;
Pointer Usage
int var = 10;
int *ptr = &var;
Embedded C Example
char *bufferPtr; // Pointer to a character buffer
Module-3 Arrays and Strings 39/50
Declaring and Using Pointers
Module-3 Arrays and Strings 40/50
Pointer Arithmetic
Pointer Operations
Pointer arithmetic allows pointers to be incremented or decremented,
effectively moving through an array or block of memory.
Example: Navigating an Array
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;
for(int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i));
}
Module-3 Arrays and Strings 41/50
Pointers and Arrays
Relationship Between Pointers and Arrays
Arrays in C are closely related to pointers; the array name can be used as a
pointer to the first element.
Example: Array Element Access
int array[3] = {1, 2, 3};
int *ptr = array;
printf("%d", *(ptr + 1)); // Outputs 2, the second element
Module-3 Arrays and Strings 42/50
Pointers and Strings
Using Pointers with Strings
Since strings are arrays of characters, pointers can be used to iterate and
manipulate strings.
Example: String Traversal
char str[] = "Hello";
char *ptr = str;
while(*ptr != ’\0’) {
putchar(*ptr++);
}
Module-3 Arrays and Strings 43/50
Pointers and Strings
Module-3 Arrays and Strings 44/50
Pointers in Functions: Pass-by-Reference
Pass-by-Reference Concept
Passing arguments by reference to a function allows the function to modify the
original value.
Example: Modifying Variables
void increment(int *value) {
(*value)++;
}
int main() {
int num = 5;
increment(&num);
printf("%d", num); // Outputs 6
}
Embedded Systems Application
This technique is frequently used in embedded systems for updating hardware
states or shared variables.
Module-3 Arrays and Strings 45/50
Example: Swapping Two Numbers Using Pointers
Swapping Function
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a = 10, b = 20;
swap(&a, &b);
printf("a: %d, b: %d", a, b); // Outputs a: 20, b: 10
}
Module-3 Arrays and Strings 46/50
Dynamic Memory Allocation in C
Heap Memory Allocation
Dynamic memory allocation involves managing memory at runtime using
functions like ‘malloc‘, ‘calloc‘, ‘realloc‘, and ‘free‘.
Embedded Systems Consideration
Careful management of dynamic memory is crucial in embedded systems
due to limited memory resources.
Module-3 Arrays and Strings 47/50
References I
Brian W. Kernighan and Dennis M. Ritchie.
The C Programming Language.
Prentice Hall, 2nd Edition, 1988.
The definitive guide to C programming by its original creators.
Stephen Prata.
C Primer Plus.
Pearson Education, 6th Edition, 2013.
Comprehensive guide to C programming, covering basic to advanced
topics.
Module-3 Arrays and Strings 48/50
References II
Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and
Clifford Stein.
Introduction to Algorithms.
MIT Press, 3rd Edition, 2009.
Provides insights into algorithmic thinking relevant to programming
challenges.
Michael Barr.
Programming Embedded Systems in C and C++.
O’Reilly Media, 1999.
A book focusing on embedded systems programming.
Michael J. Pont.
Patterns for Time-Triggered Embedded Systems.
Addison-Wesley, 2001.
Building reliable applications with the 8051 family of microcontrollers.
Module-3 Arrays and Strings 49/50
References III
GeeksforGeeks - C Programming Language.
https://www.geeksforgeeks.org/c-programming-language/
A comprehensive online resource for learning C with examples and
tutorials.
Learn C and C++ Programming - Cprogramming.com.
https://www.cprogramming.com/
An online portal offering tutorials and explanations on C and C++
programming.
Module-3 Arrays and Strings 50/50