Embeddedcmodule
Embeddedcmodule
Arrays and
Strings
Dr. Markkandan S
Outline
1 Introduction to Arrays
2 One-Dimensional Arrays, Multi-Dimensional
3 Arrays 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
10 Pointer Arithmetic
Functions
11
9
Pointers and to
Introduction Arrays, Strings, Functions
12 Introduction to Structures
Pointers
13 Accessing Structure Members
14 Structures and Functions
15 Introduction to Unions
16 Structures vs Unions
i n t sum = 0 ;
f o r ( i n t i = 0 ; i < 5; i+
+) { sum += a r r a y [ i ] ;
}
Embedded Systems Tip
Standard C Example
i n t main() {
i n t values[5] = { 5 , 10, 15, 20,
25}; i n t sum = 0 ;
f o r ( i n t i = 0 ; i < 5; i+
+) { sum += v a l u e s [ i ] ;
}
printf("Sum o f values: %d\n", sum);
return 0 ;
}
Definition
Multi-dimensional arrays are arrays of arrays.
They are used to represent data in more than one dimension, such
as matrices.
Example
multiArr[0][1] = 5; / / Element at row 0, column 1 t o
5
Declaration Syntax
type arrayName[size1][size2];
Embedded C Context
Such arrays can represent physical layouts in hardware, like an LED
matrix, with each element controlling the state of an LED.
Initialization Syntax
type arrayName[size1][size2] = { { v a l 1 , v a l 2 } , { . . . } } ;
Standard C Example
i n t m a t r ix [ 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.
Accessing Elements
Use row and column indices to access elements in a multi-
dimensional array.
arrayName[row][column]
Standard C Example
i n t value = m a t r i x [ 1 ] [ 2 ] ; / / Accesses the element a t
second r
Embedded C Context
Standard C Example
i n t array[5];
i n t * p t r = array;
printf("%p %p", p t r , p t r + / / Prints contiguous
1); addresse
Embedded C Application
Directly manipulating memory addresses is common in embedded
systems, for instance when interfacing with hardware registers.
i n t linearSearch(int a r r [ ] , i n t s iz e , i n t value)
{ f o r ( i n t i = 0; i < s iz e ; i++) {
i f ( a r r [ i ] == value) return i ;
}
return - 1 ; / / Value not found
}
Embedded C Scenario
Strings are often used for storing data read from or to be written
to peripherals, like displays in embedded systems.
Embedded C Example
char errorMessage[20] = "Error Code: " ;
Note
String initialization automatically includes the null
terminator.
Embedded C Considerations
In embedded systems, functions like ‘sprintf‘ and ‘sscanf‘ are used
for formatting strings to interact with hardware or protocol
messages.
Common Functions
Embedded C Application
String concatenation might be used in embedded systems for creating
log messages or protocol frames.
Function Definition
void functionName(parameters) {
/ / Code t o execute
}
Note
Function prototypes are often declared in header files, while definitions
are in source files.
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.
Working of Function in C
# i n c l u d e <stdio.h>
f - - - Function Defination
i n t s u m ( i n t a, i n t b)
r - { 1 -
Function return a + b; Function
Returning } Calling
Valu
e
i n t main()
{
'----- i n t a d d =ls u m (10, 30);
p r i n t f (" S u m i s ; %d",
add); r e t u r n 0 ;
}
Dr. Markkandan 5 Module-3 Arrays and
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.
{
*counter = 0 ;
} Dr. Markkandan S Module-3 Arrays and 30/103
The Return Statement and Return Types
i n t a = 5, b =
10;
i n t maximum
Embedded = max(a, b ) ;
C Usage
printf("Maximum: %d",
maximum);
Embedded C Consideration
Stack size is limited in embedded systems. Recursive functions or
deep function calls can lead to stack overflow.
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
i n t f a c t o r i a l ( i n t n) {
i f (n <= 1) return 1;
return n * f a c t o r i a l ( n - 1 ) ;
}
Embedded C Note
i n t f a c t o r i a l ( i n t n) {
i f (n <= 1) return 1;
return n * f a c t o r i a l ( n - 1 ) ;
}
i n t main() {
i n t num = 5 ;
p r i n t f ( " F a c t o r i a l of %d i s %d", num,
f act orial(num )) ; return 0;
}
a
[ l . i n t a =S 5 J Va riable 'a' Created
J - - - - - - '
Memory Address= 1010
a ptr1
a ptr1
[ 3 . printf ("o/od
","pt r l ); J ' - - -5 ) ---------- [ _ 1_0 10 ,
Memory Memory
Address= 1010 Add ress= 2456
Pointer Declaration
type *pointerName;
Pointer Usage
i n t var = 10;
in t *ptr =
&var;
Embedded C Example
char
* b u ff e r P t r ;
/ / Pointer t o a
character Dr. Markkandan S Module-3 Arrays and 39/103
Declaring and Using Pointers
- .....-- ---- - --- ---.----- - ---- -----
--- ...·...
int num=90;
int *ptr =&nu m;
·.. / . ........ ...... ..... ...........-
Vaiable name
Pointer
1,...
va riab ·.·
: va
le num
lue
lo1004
ptr
2000 1004
Add
/
ress
Dr. Markkandan 5 Module-3 Arrays and
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
•i n t array[3] = { 1 , 2,
3 } ; i n t * p t r = array;
•pr in t f ( " % d " , * ( p t r +
1));
// Outputs 2 , the
Dr. Markkandan S Module-3 Arrays and 42/103
Pointers and Strings
value H e l l 0 \0
address
II
5000 500
1
500
2
5003 5004 5005
variable st rPt r t
8000 9000
value
address
Swapping Function
void swap(int * x , i n t * y )
{ i n t temp = * x ;
*x = * y ;
*y = temp;
}
i n t main() {
i n t a = 10, b = 20;
swap(&a, &b);
p r i n t f ( " a : %d, b : %d",
a , b ) ; / / Outputs
a : 20, b : 10
}
What is a Structure?
A structure in C is a user-defined data type that allows to combine
data items of different kinds.
Structure Definition
s t r u c t MyStruct
{ i n t in t e ge r ;
char character;
};
s t r u c t MyStruct
array[2];
array[ 0] . int eger = 5;
array[0].character =
’ X ’ ; array[ 1] . int eger =
15; array[1].character =
’Y’;
Introduction to Unions
A union is a special data type in C that allows storing different data
types in the same memory location.
union MyUnion u ;
u.intVar = 5 ;
p r i n t f ( " I n t e g e r : %d",
u . i n t Va r ) ; u.charVar = ’ A ’ ;
print f (" Charact er: %c",
Embedded
u.charVar);Systems Application
Memory Allocation
Structures allocate memory for each member separately, while unions
share memory among all members, using the size of the largest
member.
Example
A structure with an int and a char will have a size larger than the sum
of both, whereas a union will have the size of the int, the larger
member.
Considerations for Embedded Systems
Example
struct {
unsigned i n t lowVoltage: 1;
unsigned i n t highTemperature:
1 ; unsigned i n t systemFailure:
1;
} statusFlags;
Embedded Systems Usage
Parsing Strings
String parsing involves breaking down a string into tokens or
extracting specific information from it.
Common Techniques
Using ‘strtok‘ for tokenizing strings.
Extracting substrings using ‘substring‘
functions. Searching for patterns within strings.
Optimizing Performance
Inline functions and macros are used to reduce the overhead of
function calls, particularly in small, frequently used functions.
Function Pointers
A function pointer is a pointer that points to a function. This allows
for dynamic function calls and passing functions as arguments to other
functions.
s t r u c t Event {
s t r u c t Date
eventDate; char
description[50];
};
s t r u c t Event myEvent =
{ { 1 , 1 , 2022},
Embedded "New
Systems Year
Context
Celebration"}
Dynamic Memory in C
Pointers are integral to dynamic memory management in C,
providing flexibility and control over memory allocation.
Linked List in C
A linked list is a dynamic data structure that can grow and shrink at
runtime. It consists of nodes that contain data and a pointer to the
next node.
Defining a Node
s t r u c t Node {
i n t data;
s t r u c t Node *next;
};
Understanding Endianness
•Endianness refers to the order of bytes in multi-byte data types.
Structures and unions must be used carefully to account for endianness
in data communication.
Challenge
Given an array of integers, write a function to reverse the array
using pointers.
Solution
void reverseArray(int * a r r, i n t size)
{ in t *start = arr;
i n t *end = a r r + size - 1;
while ( s t a r t < end) {
i n t temp = * s t a r t ;
*start++ = *end;
*end-- = temp;
}
}
Challenge
Write a C program to find the length of a string using a
pointer.
Solution
i n t stringLength(char * s t r )
{ char * p t r = s t r ;
i n t len = 0 ;
while ( * p t r != ’ \ 0 ’ )
{ len++;
ptr++;
}
return l e n ;
}
Challenge
Create a function using pointers to swap the values of two
integers.
Solution
void swap(int * a , i n t *b)
{ i n t temp = * a ;
*a = * b ;
*b = temp;
}
Challenge
Given a pointer to the start of an integer array, write a function
to compute the sum of its elements.
Solution
i n t arraySum(int * a r r, i n t n)
{ i n t sum = 0 ;
f o r ( i n t i = 0 ; i < n; i+
+) { sum += * ( a r r + i ) ;
}
return sum;
}
Challenge
Write a C function to concatenate two strings using
pointers.
Solution
void concatenate(char *dest, const char * s r c )
{ while (* dest ) dest++;
while ( * s r c ) *dest++ = *src++;
*dest = ’ \ 0 ’ ;
}
Scenario Description
•Develop a function in Embedded C to process data from multiple
sensors. Each sensor’s data is stored in an array. The function should
calculate the average value of each sensor’s data.
Embedded C Application
Explanation
This function iterates over an array of sensor readings, calculates the
total sum, and then returns the average.
Scenario Description
Implement a buffer management system in Embedded C to store and
retrieve messages from a communication interface, ensuring data
integrity and efficient memory usage.
Embedded C Significance
Effective buffer management is crucial in embedded systems for
handling data communication and preventing buffer overflows or data
loss.
char readFromBuffer() {
char data = buffer[head];
head = (head + 1) % BUFFER_SIZE;
return data;
}
Explanation
Scenario Description
•Create a protocol in Embedded C to control various devices connected
to a microcontroller, using function pointers for modularity and ease of
maintenance.
Embedded C Context
OA T ! c
@
A
1
!!
Dr. Markkan da n S Module-3 Arrays and
Tower of Hanoi Problem
Objective: Move all disks from one peg to another, with only one
disk moved at a time, and a larger disk cannot be placed on top of
a smaller disk.
Uses recursion to solve the problem elegantly.
Implementation in C demonstrates arrays for pegs, recursive
function calls, and visual representation of the pegs’ state.
C Program Highlights:
printPegs function to display the pegs.
moveDisk function to move a disk from one peg to
another. Recursive towerOfHanoi function to solve the
problem.
2D array pegs to represent the state of each peg.
Example Usage:
Initial setup with n disks on the first peg.
Recursive calls to move disks between
pegs. Visual output after each move.S
Dr. Markkandan Module-3 Arrays and 100/103
References I