0% found this document useful (0 votes)
12 views

Embedded C Programming in a Nutshell

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Embedded C Programming in a Nutshell

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 532

Embedded C Programming in a

Nutshell: A Hands-on Course


without Hardware

Restricted Circulation | L&T Technology Services | www.LTTS.com


Agenda

Embedded C

Data Types

Modifiers and Qualifiers

Operators

Expressions

6 Loops & Condition Statements

7 Arrays

8 Functions
Refresher on C

Restricted Circulation | L&T Technology Services | www.LTTS.com


C language for Embedded Systems
• C-language is always a preferred choice for Embedded software development because of
the following reasons:
• C supports low-level access through pointers
• C-language is processor independent
• C-data types are suitable for Embedded Systems because these data types are portable.
• C supports Bit Manipulation, Memory management, and multithreading features.
Additional Ref: Board and Chip Vendors – eLi
nux.org
Additional Ref: Board and Chip Vendors – eLi
nux.org
Embedded C Coding Standard | Barr Group
Embedded System Development Coding Reference Guide
: Diode

: LED

: Resistor

: Ground

: Power (Vcc/Vdd)
: Transistor

: 7 Segment Display

: Button/Switch
Memory Layout

Restricted Circulation | L&T Technology Services | www.LTTS.com


C Memory Model

Command Line
Arguments
• Memory representation of a typical C
Stack
program will have the following
Hole
sections:
Heap
• Code Segment
• Data Segment (Initialized/Uninitialized)
Data Segment • Dynamic Heap
• Stack
Text Segment

Program
Sections
Code Segment (Text Segment)
• Contain simple text part of the code containing
the executable instruction
Command Line
Arguments
Stack
• ‘Read-only’ memory, to avoid the instruction
Hole
modification
• Generally, below heaps and stack, so that
Heap overflow will not have any overwrite on the
code segment
Data Segment

Text Segment

Program
Sections
Initialized Data Segment
• Initialized global variables will be stored in this memory location
• This segment can be further classified into read-only section and read-write area
• Example: char s[ ] = “Hello World” Command Line Command Line
Arguments Arguments
• Character literal will be stored in initialized read-only area Stack Stack
• Character pointer variable in the initialized read-write data Hole
Hole

Uninitialized Data Segment Heap Heap

• This is also called as ‘bss’ segment (block start symbol)


Block Started by Symbols (.bss)
Data Segment Data Segment (.data)

• Global variables and static variables are stored in this segment Text Segment Text Segment

Program Program
Sections Sections
Stack
• A typical stack frame will contain
• Memory space for arguments
Command Line
Arguments • Space for local variables
Stack
• Return location
Hole
• Stack is usually managed by compiler, One
Heap
stack frame is created at each function call
• Usually, a stack frame is destroyed during
Data Segment
every function exit
Text Segment • Will have dedicated register to keep track
Program
of push and pop
Sections
• May contain one or more stack frames
based on the application, n number of
functions create n number stack frames
• Stack ‘Issues’
Heap
• Variables that are required for a long-term
storage and that requires to persist across
Command Line
Arguments multiple function calls are stored in ‘Heap
Stack
Memory’
Hole
• All dynamically allocated memory (i.e
Heap
memory allocated in runtime) are
allocated in the ‘Heap’ memory
Data Segment
• Programmer has to explicitly deallocate
Text Segment
the allocated memory

Program
Sections
GCC Command
• size <name.exe>
• Display the different memory segment with size
Storage Class

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage Class
• The storage classes decide the following entities:
• Lifetime
• Visibility
• Memory Location
• Default value
• Storage classes in C are
• Automatic
• External
• Static
• Register
Storage Class – “automatic”
• In the case of auto variables, the memory is allocated automatically during runtime.
• The visibility of the auto variable is only within the defined block.
• The scope of the auto variable is only within the defined block.
• The default value of an auto variable is garbage.
• The allocated memory to an auto variable is freed after the exit block.
• ‘auto’ is the keyword used to define the automatic variables.
• By default, every local variable is automatic in the C program

Variable Storage Class Scope Lifetime Memory Linkage

Local auto Block Between function / block entry and exit Stack No
Example Code 1
#include <stdio.h>

int inc(int n) {
int res;
Stac
k
res = n + 1; n=0 Stack
return addr to caller Frame
return res; of main()
res = ?
} Stack
return addr to main Frame
n=0 of inc()
int main() {
int n = 0;

printf(“%d\n”, inc(n));

return 0;
}
Storage - Automatic
Class
Example Code 1
#include <stdio.h>

int inc(int n) {
int res;
Stac
k
res = n + 1; n=0 Stack
return addr to caller Frame
return res; of main()
res = 1
} Stack
return addr to main Frame
n=0 of inc()
int main() {
int n = 0;

printf(“%d\n”, inc(n));

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Automatic
Class
Example Code 2
#include <stdio.h>

int main()
{
int i = 0; Stac
// int i = 0; // One Definition Rule k
i=0
I = 10 Stack
{ Frame
j=0
int i = 10; of main()
return addr to caller
int j = 0;

printf(“i %d\n”, i);


}

printf(“i %d\n”, i);


// printf(“j %d\n”, j);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Register
• The 'Register' storage class variables will have the memory allocated into the CPU
Registers.
• Usage of the ‘&’ operator on the register variable is restricted.
• This storage class helps to access the variables faster than the other ‘Auto’ variables.
• Although the register storage class is used, it is the compiler’s choice to store the
variables in the register.
• Pointer variables can also be stored in the register.
• Static variables cannot be stored in the CPU Registers.

Variable Storage Class Scope Lifetime Memory Linkage

auto Block Between function / block entry and exit Stack No


Local
register Block Between function / block entry and exit Register / Stack No
Storage - Register
Class
Example Code 3

#include <stdio.h>

int main()
{
register int i = 0;
// int *p = &i;

// scanf(“%d”, &i);
printf(“i is %d\n”, i);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Register
Class
Example Code 3
#include <stdio.h>

int main()
{
register int i = 0; Stack
// int *p = &i; Stack
return addr to caller Frame
// scanf(“%d”, &i); of main()
printf(“i is %d\n”, i);

return 0;
} CPU CPU
Register
i=0

Restricted Circulation | L&T Technology Services | www.LTTS.com


Static
• Can hold their value in the multiple function calls.
• The visibility of the local static variables is only within the defined block.
• A similar static variable can be declared many times but can be assigned only once.
• A static integral variable is initialized to 0, otherwise null.
• The visibility of the static global variables is within the file in which they are declared.
• The 'static' keyword is used to define the static variable.

Variable Storage Class Scope Lifetime Memory Linkage

auto Block Between function / block entry and exit Stack No

Local register Block Between function / block entry and exit Register / Stack No

static Block Between program entry and exit Data Segment No


Storage - Automatic
Class
Example Code 4
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
int event_cnt = 0;

// Some operation to be done

return ++event_cnt;
}

int main() {
while (1) {
printf(“%d\n”, event_tracker());
sleep(1);
}

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Automatic - The Problem
Class
Example Code 4
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
int event_cnt = 0; Stack
Stack
// Some operation to be done return addr to caller Frame
of main()
return ++event_cnt;
}

int main() {
while (1) {
printf(“%d\n”, event_tracker());
sleep(1);
}

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Automatic - The Problem
Class
Example Code 4
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
int event_cnt = 0; Stack
Stack
// Some operation to be done return addr to caller Frame
of main()
event_count = 0 Stack Frame
return ++event_cnt; of
return addr to main
} event_tracker()

int main() {
while (1) { // 1st Iteration
printf(“%d\n”, event_tracker());
sleep(1);
}

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Automatic - The Problem
Class
Example Code 4
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
int event_cnt = 0; Stack
Stack
// Some operation to be done return addr to caller Frame
of main()
event_count = 1 Stack Frame
return ++event_cnt; of
return addr to main
} event_tracker()

int main() {
while (1) { // 1st Iteration
printf(“%d\n”, event_tracker());
sleep(1);
}

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Automatic - The Problem
Class
Example Code 4
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
int event_cnt = 0; Stack
Stack
// Some operation to be done return addr to caller Frame
of main()
event_count = 0 Stack Frame
return ++event_cnt; of
return addr to main
} event_tracker()

int main() {
while (1) { // 2nd Iteration
printf(“%d\n”, event_tracker());
sleep(1);
}

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Automatic - The Problem
Class
Example Code 4
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
int event_cnt = 0; Stack
Stack
// Some operation to be done return addr to caller Frame
of main()
event_count = 1 Stack Frame
return ++event_cnt; of
return addr to main
} event_tracker()

int main() {
while (1) { // 2nd Iteration
printf(“%d\n”, event_tracker());
sleep(1);
}

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Automatic - The Problem
Class
Example Code 4
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
int event_cnt = 0; Stack
Stack
// Some operation to be done return addr to caller Frame
of main()
event_count = 0 Stack Frame
return ++event_cnt; of
return addr to main
} event_tracker()

int main() {
while (1) { // nth Iteration
printf(“%d\n”, event_tracker());
sleep(1);
}

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Automatic - The Problem
Class
Example Code 4
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
int event_cnt = 0; Stack
Stack
// Some operation to be done return addr to caller Frame
of main()
event_count = 1 Stack Frame
return ++event_cnt; of
return addr to main
} event_tracker()

int main() {
while (1) { // nth Iteration
printf(“%d\n”, event_tracker());
sleep(1);
}

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Static Local - The Solution
Class
Example Code 5
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
static int event_cnt = 0;
// Compile
time
// Some operation to be done

return ++event_cnt;
}

int main() {
while (1) { Data Segment
(.bss)
printf(“%d\n”, event_tracker()); event_count = 0
sleep(1); Part of .o file, will be
} allocated
while the program loaded
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Static Local - The Solution
Class
Example Code 5
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
static int event_cnt = 0; // Compile time Stack
Stack
// Some operation to be done return addr to caller Frame
of main()
return ++event_cnt;
}

int main() {
while (1) { Data Segment
(.bss)
printf(“%d\n”, event_tracker()); event_count = 0
sleep(1); Part of .o file, will be
} allocated
while the program loaded
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Static Local - The Solution
Class
Example Code 5
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
static int event_cnt = 0; // Compile time Stack
Stack
// Some operation to be done return addr to caller Frame
of main()
Stack Frame
return addr to main of
return ++event_cnt;
event_tracker()
}

int main() {
while (1) { // 1st Iteration Data Segment
(.bss)
printf(“%d\n”, event_tracker()); event_count = 0
sleep(1); Part of .o file, will be
} allocated
while the program loaded
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Static Local - The Solution
Class
Example Code 5
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
static int event_cnt = 0; // Compile time Stack
Stack
// Some operation to be done return addr to caller Frame
of main()
Stack Frame
return addr to main of
return ++event_cnt;
event_tracker()
}

int main() {
while (1) { // 1st Iteration Data Segment
(.bss)
printf(“%d\n”, event_tracker()); event_count = 1
sleep(1); Part of .o file, will be
} allocated
while the program loaded
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Static Local - The Solution
Class
Example Code 5
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
static int event_cnt = 0; // Compile time Stac
k Stack
// Some operation to be done return addr to caller Frame
of main()
Stack Frame
return addr to main of
return ++event_cnt;
event_tracker()
}

int main() {
while (1) { // 2nd Iteration Data Segment
(.bss)
printf(“%d\n”, event_tracker()); event_count = 1
sleep(1); Part of .o file, will be
} allocated
while the program loaded
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Static Local - The Solution
Class
Example Code 5
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
static int event_cnt = 0; // Compile time Stac
k Stack
// Some operation to be done return addr to caller Frame
of main()
Stack Frame
return addr to main of
return ++event_cnt;
event_tracker()
}

int main() {
while (1) { // 2nd Iteration Data Segment
(.bss)
printf(“%d\n”, event_tracker()); event_count = 2
sleep(1); Part of .o file, will be
} allocated
while the program loaded
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Static Local - The Solution
Class
Example Code 5
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
static int event_cnt = 0; // Compile time Stac
k Stack
// Some operation to be done return addr to caller Frame
of main()
Stack Frame
return addr to main of
return ++event_cnt;
event_tracker()
}

int main() {
while (1) { // nth Iteration Data Segment
(.bss)
printf(“%d\n”, event_tracker()); event_count = 2
sleep(1); Part of .o file, will be
} allocated
while the program loaded
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Static Local - The Solution
Class
Example Code 5
#include <stdio.h>
#include <unistd.h>

int event_tracker(void) {
static int event_cnt = 0; // Compile time Stack

Stack
// Some operation to be done return addr to caller Frame
of main()
Stack Frame
return addr to main of
return ++event_cnt;
event_tracker()
}

int main() {
while (1) { // nth Iteration Data Segment
(.bss)
printf(“%d\n”, event_tracker()); event_count = n
sleep(1); Part of .o file, will be
} allocated
while the program loaded
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Static Local
Class
Example Code 6
#include <stdio.h>

int updated_count(void) {
int current_val;
// Get the event val for other function
return current_val;
}

int event_tracker(void) {
static int event_cnt = updated_count();
// Some operation to be done
return ++event_cnt;
}

int main() {
// Some logic similar to previous example
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Static Local - The Problem
Class
Example Code 6
#include <stdio.h>
Problem: For static variable values
int updated_count(void) { cannot be updated at run-time
int current_val;
<ex>
// Get the event val for other function
static int i=0  Valid
return current_val;
static int i=k  Not-Valid
}

int event_tracker(void) {
static int event_cnt = updated_count();
// Some operation to be done
return ++event_cnt;
}

int main() {
// Some logic similar to previous example
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Storage - Static Local - The Solution
Class
Example Code 7
#include <stdio.h>

int updated_count(void) {
int current_val;
// Get the event val for other function
return current_val;
}

int event_tracker(void) {
static int event_cnt;
event_cnt = updated_count();
// Some operation to be done
return ++event_cnt;
}

int main() {
// Some logic similar to previous example
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Extern
• ‘extern’ notifies the compiler that the variable declared has an external linkage (it may
be defined in another file)
• ‘extern’ variables are usually not allocated with any memory.
• The default initial value is ‘0’, and it can be initialized as only a global variable.
• It can be declared multiple times but can be initialized only once.
• The compiler notifies an error for uninitialized extern variables.
Extern
• Example:

int a; //Declaration & extern int a; //Declaration


Definition Compiler never throws
Declaration – a is a
Declaration – a is a error
variable of type integer.
variable of type integer Linker throws error if it
It says to the compiler
Definition – Allocate couldn’t be able to find
variable “a” is defined
Memory the definition
somewhere reuse it

Variable Storage Class Scope Lifetime Memory Linkage

auto Block Between function / block entry and exit Stack No

Local register Block Between function / block entry and exit Register / Stack No

static Block Between program entry and exit Data Segment No

Global extern Program Between program entry and exit Data Segment Internal / External
Storage
Class
Sample Code
#include <stdio.h>

void timer_isr(void) {
int overflow_cnt;

if (overflow_cnt == 1000)
secs++;

overflow_cnt++;
}

int main() {
if (secs == 60)
// Required Operation to be done

return 0;
}
Storage - Problem
Class
Sample Code
#include <stdio.h>

void timer_isr(void) {
Note: ISR Function neither
int overflow_cnt;
accepts nor return any thing.
<ex>
if (overflow_cnt == 1000)
secs++; “secs” - variable

overflow_cnt++;
}

int main() {
if (secs == 60)
// Required Operation to be done

return 0;
}
Storage - Global - Solution
Class
Sample Code
#include <stdio.h>

int secs;

void timer_isr(void) {
int overflow_cnt;

if (overflow_cnt == 1000)
secs++;

overflow_cnt++;
}

int main() {
if (secs == 60)
// Required Operation to be done

return 0;
}
Storage - Global
Class
Example Code 8
#include <stdio.h>

int x;

void foo(void) {
x++;
}

int main() {
foo();

printf(“%d\n”, x);

return 0;
}
Storage - Global - Multifile
Class
Example Code 9 – main.c bar.c
#include <stdio.h> #include <stdio.h>

int x; int x; //Tentative Definition

void foo(void) { void bar(void) {


x++; x++;
} }

int main() {
foo();
printf(“%d\n”, x);
Output:
bar(); 1
printf(“%d\n”, x); 2

return 0;
}
Storage - Global - Multifile
Class
Example Code 10 – main.c bar.c
#include <stdio.h> #include <stdio.h>

int x = 10; int x; //Tentative Definition

void foo(void) { void bar(void) {


x++; x++;
} }

int main() {
foo();
printf(“%d\n”, x);
Output:
bar(); 11
printf(“%d\n”, x); 12

return 0;
}
Storage - Global - Multifile
Class
Example Code 11 – main.c bar.c
#include <stdio.h> #include <stdio.h>

int x = 10; int x = 5; //Definition

void foo(void) {
x++; void bar(void) {
} x++;
}
int main() {
foo();
printf(“%d\n”, x);
Output:
bar(); Error: 2 Defined Same
printf(“%d\n”, x); Global Variable cannot be
placed in same memory
return 0;
}
Storage - Global - Multifile
Class
Example Code 12 – main.c bar.c
#include <stdio.h> #include <stdio.h>

int x = 10; extern int x; //Declaration

void foo(void) { void bar(void) {


x++; x++;
} }

int main() {
foo();
printf(“%d\n”, x);
Output:
bar(); 11
printf(“%d\n”, x); 12

return 0;
}
Storage - Memory Layout
Class

Variable Storage Class Scope Lifetime Memory Linkage

auto Block Between function / block entry and exit Stack No

Local register Block Between function / block entry and exit Register / Stack No

static Block Between program entry and exit Data Segment No

extern Program Between program entry and exit Data Segment Internal / External
Global
static File Between program entry and exit Data Segment Internal
Storage - Global - Multifile - Problem
Class
Example Code 13 – main.c bar.c
#include <stdio.h> #include <stdio.h>

static int x = 10; // File Scope Variable extern int x;

void foo(void) { void bar(void) {


x++; x++;
} }

int main() {
foo();
printf(“%d\n”, x);
Output:
bar(); Error: In main.c int x
printf(“%d\n”, x); becomes file scope, so
extern int x cannot be
return 0; linked
}
Storage - Global - Multifile - Problem
Class
Example Code 14 – main.c bar.c
#include <stdio.h> #include <stdio.h>

int x = 10; // File Scope Variable extern int x;

void foo(void) { static void bar(void) {


x++; x++;
} }

int main() {
foo();
printf(“%d\n”, x);
Output:
bar(); Error: In bar.c Function
printf(“%d\n”, x); bar() is a file scope so
cannot be linked with
return 0; main.c
}
Storage - Global
Class
Example Code 15
#include <stdio.h>

int i = 10;

void foo(void) {
extern int i;

printf(“%d\n”, i);
}

int main() {
int i; Output:
10
foo(); 0
printf(“%d\n”, i); Extern int i is linked with
global variable I  bcoz
return 0; “extern” says go outside
} of my scope and find the
definition
Storage - Global
Class
Example Code 16
#include <stdio.h>

void foo(void) {
extern int i;

printf(“%d\n”, i);
}

static int i = 10; // Not allowed!!

int main() {
int i; Output:
Error: initially I is defined
foo(); as extern but later is
printf(“%d\n”, i); limited as file scope
which throws error
return 0;
}
Storage - Global
Class
Example Code 16
#include <stdio.h>
static int i = 10; // allowed!!

void foo(void) {
extern int i;

printf(“%d\n”, i);
}

int main() {
int i; Output:
10
foo(); 0
printf(“%d\n”, i);

return 0;
}
Thank You !
Applied C – Operators
Bitwise
Operators - Bitwise


While working Low Level System Programming or Embedded System
Programming we may have to deal with accessing bit of Registers /
Variable

So in any case if you want deal with bits of data, C provides us Bitwise
Operators

They performs operations on bits

All the operands will be treated as Integers

The result of the evaluation will be Integers
Operators - Bitwise


6 operators

& - AND

Can be used to get bit(s) from the operand

Can be used to clear bit(s) of the operand

| - OR

Used to set bit(s) of the operand

^ - XOR

Used to toggle bit(s) of the operand

~ - Compliment

Used to invert bits of the operand
Operators - Bitwise


6 operators

<< - Left Shift

Shift bits towards left side of the operand

>> - Right Shift

Shift bits towards right side of the operand
Operators – Bitwise
• 6 Operators
• Binary Operator (&, |, ^, << and >>)
• Need 2 Operators
• Unary Operator (~)
• Need Single Operand
• Works just like Logic Gates
Operators - Bitwise

AND OR XOR Complemen


t
A B O A B O A B O A O
0 0 0 0 0 0 0 0 0 0 1
0 1 0 0 1 1 0 1 1 1 0
1 0 0 1 0 1 1 0 1
1 1 1 1 1 1 1 1 0

A 0 0 1 1 A 0 0 1 1 A 0 0 1 1 A 0 0 1 1
B 0 1 0 1 B 0 1 0 1 B 0 1 0 1
O 0 0 0 1 O 0 1 1 1 O 0 1 1 0 O 1 1 0 0
Operators - Bitwise

Left Right
Shift Shift
Ideal Sign Bit
Case Fill
A 1 0 0 1 A 1 0 0 1 A 1 0 0 1 A 0 1 0 1
1 0 0 1 << 1 0 0 1 >> 1 0 0 1 >> 0 1 0 1 >>
0 0 0 0
0 0 1 0 << 0 1 0 0 >> 1 1 0 0 >> 0 0 1 0 >>
1 1 1 1
0 1 0 0 << 0 0 1 0 >> 1 1 1 0 >> 0 0 0 1 >>
2 2 2 2
1 0 0 0 << 0 0 0 1 >> 1 1 1 1 >> 0 0 0 0 >>
3 3 3 3
0 0 0 0 << 0 0 0 0 >> 1 1 1 1 >> 0 0 0 0 >>
4 4 4 4
Operators -
Bitwise

What is the easiest way painting the below number on a wall on
multiple locations?
Operators - Bitwise


Mask

A cover that protect certain region

Or, A cover that exposes certain region
Operators - Bitwise


Mask

A cover that protect certain region

Or, A cover that exposes certain region

Stencil
Operators - Bitwise


Mask

A cover that protect certain region

Or, A cover that exposes certain region

Stencil
Operators - Bitwise


Mask

A cover that protect certain region

Or, A cover that exposes certain region

So technically, masking is exposing certain bit so that we can operate
on them like

Get Bit(s)

Set Bit(s)

Clear Bit(s)

...
Operators - Bitwise

7 6 5 4 3 2 1 0 Bit Position

Get 6th Bit 1 1 1 0 0 1 1 0 Register to be modified

0 1 0 0 0 0 0 0 Mask to get 6th bit position

& 0 1 0 0 0 0 0 0 If bit 6 is 1, result != 0, else 0

Clear 6th Bit 1 1 1 0 0 1 1 0 Register to be modified

1 0 1 1 1 1 1 1 Mask to clear 6th bit position

& 1 0 1 0 0 1 1 0 6th bit will be cleared


Operators - Bitwise

7 6 5 4 3 2 1 0 Bit Position

Set 4th Bit 1 1 1 0 0 1 1 0 Register to be modified

0 0 0 1 0 0 0 0 Mask to set 4 bit position

| 1 1 1 1 0 1 1 0 Bit 4 is set to 1

Toggle 4th Bit 1 1 1 1 0 1 1 0 Register to be modified

0 0 0 1 0 0 0 0 Mask to Toggle 4th bit position

^ 1 1 1 0 0 1 1 0 bit 4 will be toggled

0 0 0 1 0 0 0 0 Mask to Toggle 4tbit position

^ 1 1 1 1 0 1 1 0 bit 4 will be toggled


Thank You !
Applied C - User Defined
Datatypes

Restricted Circulation | L&T Technology Services | www.LTTS.com


Outline
• Enum
• Typedef
• Structures
• Unions
Enumerated Datatype

Restricted Circulation | L&T Technology Services | www.LTTS.com


Enumerated Datatype
• Enumerated datatype is used when the user require to define the values of the variable to be
taken
• With enum (Enumerated Datatype) one can design a new datatype called ‘level_t’ which can
have 3 different possible values – ‘LOW’ ‘MEDIUM’ ‘HIGH’
• Now the variables with type ‘level_t’ can take the above-mentioned possible values

enum level_t { enum level_t{ //anonymous


//anonymous LOW = 0x10,
LOW, MEDIUM = 0x11,
MEDIUM, HIGH = 0x20
HIGH }level_t;
};
level_t level;
enum level_t level; enum level=MEDIUM;
level=MEDIUM; //if(level==HIGH)
//if(level==HIGH)
Enum Uses:

• Enums are used in creating a user-


enum Color {
defined datatypes for holding some RED,
predefined enumerated values GREEN,
BLUE,
• This improves the readability of the BLACk,
program WHITE,
YELLOW
• Better alternative to strings, symbolic };
constants or global const variables to typedef enum Color
color_t;
avoid magic constants color_t code;
• Internally enums assigns the integer //enum Color code;
code=GREEN;
values in specific order for each of the //if(code==BLUE)
possible values //case RED, in switch
//arr[RED]
• The default integer values can also be
changed by initializing the possible
values Enum :
 Reference-1
Example 1
#include<stdio.h>
int main()
{
enum Switch_State
{
Output:
off,low,medium,high
}; Motor2_State is High
Motor1_State = 0
enum Switch_State
Motor1_State,Motor2_State;
Motor1_State=off;
Motor2_State=high;
if(Motor2_State==high)
printf("\n Motor2_State is High");
printf("\n Motor1_State=
Example 2
#include<stdio.h>
int main()
{
enum Switch_State
{
Output:

off=0,low=10,medium=100,high=1000 Motor1_State is Off


Motor2_State = 1000
};
enum Switch_State
Motor1_State,Motor2_State;
Motor1_State=off;
Motor2_State=high;
if(Motor1_State==off)
printf("\n Motor1_State is off");
Typedef

Restricted Circulation | L&T Technology Services | www.LTTS.com


Typedef
• Typedef declaration helps to redefine the name of an existing variable type
• This also improves the readability of the program
• This can be applied for existing datatypes (such as int, float,double..), structure pointer,
function pointer and for enum types as well
• With the use of typedef long names in declaration can be given a short meaningful name

typedef enum { enum level_t{ //anonymous


//anonymous LOW = 0x10,
LOW, MEDIUM = 0x11,
MEDIUM, HIGH = 0x20
HIGH };
}level_t;
typedef enum level_t level;
level_t level; level level1;
level=MEDIUM; level1=MEDIUM;
//if(level==HIGH) //if(level==HIGH)
Example 1
#include<stdio.h>
int main()
{
enum Switch_State
{

off=0,low=10,medium=100,high=1000
}; Output:
enum Switch_State
Motor1_State,Motor2_State; Motor2_State is High
typedef enum Switch_State STATE; Motor1_State = 0
STATE Motor3_State; Motor3_State = 100
Motor1_State=off;
Motor2_State=high;
Motor3_State=medium;
if(Motor2_State==high)
printf("\n Motor2_State is High");
printf("\n Motor1_State=
%d",Motor1_State);
printf("\n Motor3_State=
%d",Motor3_State);
return 0;
Structure

Restricted Circulation | L&T Technology Services | www.LTTS.com


Structure

• A Structure in ‘C’ is a user-defined data type


used to group elements of different types.
Syntax :
Accessing Structure Members struct demo{
• In the previous example, a ‘demo’ structure is int x; // x and z are structure members
defined. double z;
• A type ‘demo’ variable should be declared to } ; //’demo’ is the name of the structure
access the structure members.
• Syntax for accessing the structure members
• name_of_variable.name_of_member
• (.) ‘dot’ operator is the member access
operator
Example 1
#include<stdio.h>
typedef struct
{
int x;
}demo;
Output:
int main()
Value of x is 5
{
demo a;
a.x=5
printf("Value of x is %d",a.x);
return 0;
}
Example 2
#include<stdio.h>
typedef struct
{
int x;
}demo;
Output:
int main()
{ Value of x in first instance is
5
demo a[2]; Value of x in second
a[0].x=5 instance is 10
a[1].x=10;
printf("Value of x in first instance is %d\
n",a[0].x);
printf("Value of x in second instance is
%d",a[1].x);
Union

Restricted Circulation | L&T Technology Services | www.LTTS.com


Union

• Both structures and unions are used to group a


number of different variables together. Syntax :
• But while a structure enables us treat a number union demo{
of different variables stored at different places in int x; // x and z are structure members
memory, a union enables us to treat the same double z;
space in memory as a number of different } ; //’demo’ is the name of the structure
variables.

union a Key.i
{
short int i;
char ch[2]; ADDR ADDR+1
};
union a key; Key.ch[0] Key.ch[1]
Example 1
#include<stdio.h>
typedef union
{
short int x;
char ch[2];
}demo; Output:
int main()
a.x is 512
{ a.ch[0] is 0
demo a; a.ch[1] is 2

a.x=512;
printf("a.x is %d\n",a.x);
printf("a.ch[0] is %c\n",a.ch[0]);
printf("a.ch[1] is %c\n",a.ch[1]);
return 0;
}
Applied C - Pointers
Level 1

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers

Jargon
!!

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Jargon


Special words or expression used by a profession or group that are
difficult for other to understand
- Definition from Oxford Languages

Pointer are perceived difficult, because of


this Jangonfication!!


Lets understand it with 7 simple rules

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - What is it?

“A variable which stores an address of


another variable”

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Why?

Sample Code

Parameter passing
int main()
{
int image[4096];

add_background(image);
add_border(image);
add_pattern(image);
send(image);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Why?


Parameter passing

Register or I/O Access

(0xFF0)

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Why?

Sample Code

Parameter passing
struct Test *foo1() {

Register Access // Return Structure
}

Return a more than one value from a int *foo2() {
function // Return an Array
}

void sqr_and_cube(int n, int *s, int *c) {


// Logic to get square and cube
}

int main()
{
int n = 10, s, c;

sqr_and_cube(n, &s, &c);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Why?


Parameter passing

Register Access Command Line
Arguments

Return a more than one value from a Stack

function Hole

Dynamic Memory Allocation
Heap

.BSS

Segment
(Uninitialized)

Data
Initialized

Text Segment

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - How can I use that?


Well its a bit vast topic and we need to be bit careful while dealing with
it

As said let get its details using 7 rules

Restricted Circulation | L&T Technology Services | www.LTTS.com


To be Continued ...

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7
Rules

Pointer is an Integer

Referencing and De-referencing

Pointer means containing

Pointer Types

Pointer Arithmetic

Pointing to Nothing

Static vs Dynamic Allocation

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 1 - Pointer is an Integer

5 i
CPU
5 p
RAM Integer i;
Pointer p;
Say:
i=
5;
p
=5;

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 1 - Pointer is an Integer
Rules

Any number we write on a Data bus is an Integer

Any number we write on a Address bus is pointer

Eventually its an number which goes to different busses!!, with some
exceptions

The width of that number may vary based on the system architecture

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 1 - Pointer is an Integer
Rules

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 1 - Pointer is an Integer

Example Code 1
#include <stdio.h>

typdef int * pointer;

int main()
{
int i;
pointer p;

i = 5;
p = 5;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 1 - Pointer is an Integer

Example Code 1
#include <stdio.h>

typdef int * pointer; i


int main() 100 ?
{ 0
int i;
pointer p;

i = 5;
p = 5;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 1 - Pointer is an Integer

Example Code 1
#include <stdio.h>

typdef int * pointer; i


int main() 100 ?
{ 0
int i;
pointer p;
p
i = 5; 200 ?
p = 5; 0

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 1 - Pointer is an Integer

Example Code 1
#include <stdio.h>

typdef int * pointer; i


int main() 100 5
{ 0
int i;
pointer p;
p
i = 5; 200 ?
p = 5; 0

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 1 - Pointer is an Integer

Example Code 1
#include <stdio.h>

typdef int * pointer; i


int main() 100 5
{ 0
int i;
pointer p;
p
i = 5; 200 5
p = 5; // Warning 0

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 1 - Pointer is an Integer

Example Code 1
#include <stdio.h>

typdef int * pointer; i


int main() 100 5
{ 0
int i;
pointer p;
p
i = 5; 200 5
p = (int *) 5; 0

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 1 - Pointer is an Integer

Example Code 1
#include <stdio.h>

typdef int * pointer;

int main()
{
int i;
pointer p;

i = 5;
p = (int *) 5.5; // Error

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 2 - Referencing and De-referencing

Variable

& *

Address

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 2 - Referencing and De-referencing

Example Code 2
#include <stdio.h>

int main()
{
int x;
int *p;

x = 5;
p = &x;

printf(“*p contains %d\n”, *p);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 2 - Referencing and De-referencing

Example Code 2
#include <stdio.h>

int main() x
{
int x; 100 ?
int *p; 0

x = 5;
p = &x;

printf(“*p contains %d\n”, *p);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 2 - Referencing and De-referencing

Example Code 2
#include <stdio.h>

int main() x
{
int x; 100 ?
int *p; 0

x = 5;
p
p = &x;
200 ?
printf(“*p contains %d\n”, *p); 0

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 2 - Referencing and De-referencing

Example Code 2
#include <stdio.h>

int main() x
{
int x; 100 5
int *p; 0

x = 5;
p
p = &x;
200 ?
printf(“*p contains %d\n”, *p); 0

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 2 - Referencing and De-referencing

Example Code 2
#include <stdio.h>

int main() x
{
int x; 100 5
int *p; & 0

x = 5;
p
p = &x;
200 1000
printf(“*p contains %d\n”, *p); 0

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 2 - Referencing and De-referencing

Example Code 2
#include <stdio.h>

int main() x
{
int x; 100 5
int *p; & 0 *

x = 5;
p
p = &x;
200 1000
printf(“*p contains %d\n”, *p); 0

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 2 - Referencing and De-referencing

Example Code 2
#include <stdio.h>

int main() x
{
int x; 100 5
int *p; & 0 *

x = 5;
p
p = &x;
200 1000
printf(“*p contains %d\n”, *p); 0

return 0;
}
“x ↔ *p”

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules- Rule 3 - Pointer mean Containing

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 Rules - Rule 3 - Pointer mean Containing

Example Code 3
#include <stdio.h> x 5 100
0
100
int main()
4
{ 100
int x = 5; 8
101
int *p;
2
p 1000 101
p = &x; 6
102
0
return 0; 102
} 4

Pointer pointing to a Variable = Pointer contains the Address of the Variable


Rule: “Pointing means Containing”

Restricted Circulation | L&T Technology Services | www.LTTS.com


To be Continued ...

Restricted Circulation | L&T Technology Services | www.LTTS.com


Restricted Circulation | L&T Technology Services | www.LTTS.com
Pointers - 7 Rules
Pointer Types

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
Rules

What?? types to pointers?, Why do we need it?

What the below definitions mean?
Sample Code
#include <stdio.h>

int main()
{
int *p1;
char *p2;
float *p3;
double *p4;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
Rules

What?? types to pointers?, Why do we need it?
Example Code 4
#include <stdio.h>

int main()
{
int x = 0x1234;
char y;

int *ip = &x;


char *cp = &y;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
Rules

What?? types to pointers?, Why do we need it?
Example Code
#include <stdio.h> x

int main() 100 0x1234


{ 0
int x = 0x1234;
char y;

int *ip = &x;


char *cp = &y;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
Rules

What?? types to pointers?, Why do we need it?
Example Code 4
#include <stdio.h> x y

int main() 100 0x1234 100 ?


{ 0 4
int x = 0x1234;
char y;

int *ip = &x;


char *cp = &y;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
Rules

What?? types to pointers?, Why do we need it?
Example Code 4
#include <stdio.h> x y

int main() 100 0x1234 100 ?


{ 0 4
int x = 0x1234;
char y; i
p
int *ip = &x; 200 1000
char *cp = &y; 0

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
Rules

What?? types to pointers?, Why do we need it?
Example Code 4
#include <stdio.h> x y

int main() 100 0x1234 100 ?


{ 0 4
int x = 0x1234;
char y; i c
p p
int *ip = &x; 200 1000 200 1004
char *cp = &y; 0 4

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
- Endianness
Rules

Since the discussion is on data fetching, is better to have the
knowledge on byte storage on the system which is generally know as
endianness

Endianness??

Byte ordering within a word of a system

There are 2 possibilities

Little Endian

Big Endian

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
- Endianness
Rules
Example Code 5
#include <stdio.h>

int main()
{
int x = 0x12345678;
int *ip, char *cp;

ip = &x;
cp = &x;

printf(“*ip is %d\n”, *ip);


printf(“*cp is %d\n”, *cp);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
- Endianness
Rules
Example Code 5 Little Big
#include <stdio.h> Endian Endian
x x
int main() 78 56 34 12 12 34 56 78
{
int x = 0x12345678;

0 00

0
1 0

1 00
2 0

2 00
3 00

3 00
10
10
10
1

1
1
1

1
int *ip, char *cp;

0
ip = &x;
cp = &x;

printf(“*ip is %d\n”, *ip);


printf(“*cp is %d\n”, *cp);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
- Endianness
Rules
Example Code 5 Little Big
#include <stdio.h> Endian Endian
x x
int main() 78 56 34 12 12 34 56 78
{
int x = 0x12345678;

0 00

0
1 0

1 00
2 0

2 00
3 00

3 00
10
10
10
1

1
1
1

1
int *ip, char *cp;

0
i i
p p
ip = &x; 1000 1000
200 200
cp = &x; 0 0
c c
p p
1000 1000
printf(“*ip is %d\n”, *ip); 200 200
8 8
printf(“*cp is %d\n”, *cp);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
- Endianness
Rules
Example Code 5 Little Big
#include <stdio.h> Endian Endian
x x
int main() 78 56 34 12 12 34 56 78
{
int x = 0x12345678;

0 00

0
1 0

1 00
2 0

2 00
3 00

3 00
10
10
10
1

1
1
1

1
int *ip, char *cp;

0
i i
p p
ip = &x; 1000 1000
200 200
cp = &x; 0 0
c c
p p
1000 1000
printf(“*ip is %d\n”, *ip); 200 200
8 8
printf(“*cp is %d\n”, *cp);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
- Endianness
Rules
Example Code 5 Little Big
#include <stdio.h> Endian Endian
x x
int main() 78 56 34 12 12 34 56 78
{
int x = 0x12345678;

0 00

0
1 0

1 00
2 0

2 00
3 00

3 00
10
10
10
1

1
1
1

1
int *ip, char *cp;

0
i i
p p
ip = &x; 1000 1000
200 200
cp = &x; 0 0
c c
p p
1000 1000
printf(“*ip is %d\n”, *ip); 200 200
8 8
printf(“*cp is %d\n”, *cp);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
- Endianness
Rules
Example Code 5 Little Big
#include <stdio.h> Endian Endian
x x
int main() 78 56 34 12 12 34 56 78
{
int x = 0x12345678;

0 00

0
1 0

1 00
2 0

2 00
3 00

3 00
10
10
10
1

1
1
1

1
int *ip, char *cp;

0
i i
p p
ip = &x; 1000 1000
200 200
cp = &x; 0 0
c c
p p
1000 1000
printf(“*ip is %d\n”, *ip); 200 200
8 8
printf(“*cp is %d\n”, *cp);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
- Endianness
Rules
Example Code 5 Little Big
#include <stdio.h> Endian Endian
x x
int main() 78 56 34 12 12 34 56 78
{
int x = 0x12345678;

0 00

0
1 0

1 00
2 0

2 00
3 00

3 00
10
10
10
1

1
1
1

1
int *ip, char *cp;

0
i i
p p
ip = &x; 1000 1000
200 200
cp = &x; 0 0
c c
p p
1000 1000
printf(“*ip is %d\n”, *ip); 200 200
8 8
printf(“*cp is %d\n”, *cp);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
- Endianness
Rules
Example Code 5
#include <stdio.h>
x
int main()
{ 12
char x = 0x12;

0
10
int *ip, char *cp;

0
i
cp = &x; p
1000
200
ip = &x; 0
c
p
printf(“*cp is %d\n”, *cp); 1000
200
printf(“*ip is %d\n”, *ip); 8

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
- Endianness
Rules
Example Code 5
#include <stdio.h>
x
int main()
{ 12
char x = 0x12;

0
10
int *ip, char *cp;

0
i
cp = &x; p
1000
200
ip = &x; 0
c
p
printf(“*cp is %d\n”, *cp); 1000
200
printf(“*ip is %d\n”, *ip); 8

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
- Endianness
Rules
Example Code 5
#include <stdio.h>
x
int main()
{ 12 ? ? ?
char x = 0x12;

1 00
2 00

3 00
10
int *ip, char *cp;

1
1

1
0
i
cp = &x; p
1000
200
ip = &x; 0
c
p
printf(“*cp is %d\n”, *cp); 1000
200
printf(“*ip is %d\n”, *ip); 8

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
- Endianness
Rules

So to summarize,

The type of a pointer represents it's ability to perform read or write operations
on number of bytes (data) starting from address its pointing to

Size of all different type pointers remains same

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 4 - Pointer Types
- Endianness
Rules

So to summarize,

The type of a pointer represents it's ability to perform read or write operations
on number of bytes (data) starting from address its pointing to

Size of all different type pointers remains same

Example Code 6
#include <stdio.h>

int main()
{
if (sizeof(char *) == (sizeof(long *))
printf(“Yes\n”);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Restricted Circulation | L&T Technology Services | www.LTTS.com
Pointers - 7 Rules
Pointer Arithmetic

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
Rules

Rule: “Value(p + i) = Value(p) + i * sizeof(*p)”

Lets understand the array interpretations before proceeding to this
rule

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
- Array Interpretations
Rules
Sample Code
#include <stdio.h>

int main()
{
int a[] = {10, 20, 30, 40, 50};

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
- Array Interpretations
Rules
Sample Code
a
#include <stdio.h>
Pointer to One big
int main() the first 10 variable
{ small variable
int a[] = {10, 20, 30, 40, 50}; 20

return 0; While While


} assigning to 30 using with
pointer sizeof()

40 While
While
pointer
passing to
arithmetic
functions 50
on &a

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
Rules
Example Code 7
#include <stdio.h>

int main()
{
int a[] = {10, 20, 30, 40, 50};
int *p = a;

p = p + 1;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
Rules
Example Code 7
a
#include <stdio.h>
10 100
int main() 0
{ 20 100
int a[] = {10, 20, 30, 40, 50}; 4
30 100
int *p = a;
8
40 101
p = p + 1; 2
50 101
return 0; 6
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
Rules
Example Code 7
a
#include <stdio.h>
10 100
int main() 0
{ 20 100
int a[] = {10, 20, 30, 40, 50}; 4
30 100
int *p = a;
8
40 101
p = p + 1; 2
50 101
return 0; 6
}

1000 200
0

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
Rules
Example Code 7 
p = p + 1; a
#include <stdio.h> 
The above line is interpreted as
10 100
int main() 
p = p + 1 * sizeof(data type) 0
{ 20 100
int a[] = {10, 20, 30, 40, 50};  4
Here, the array is of int type , 30 100
int *p = a; so 8
40 101
p = p + 1; 
p = p + 1 * sizeof(int) 2
50 101
return 0; 
p=p+1*4 6
}

p=p+4

Here p = 1000 so p


p = 1000 + 4 1004 200
0

p = 1004

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
Rules
Example Code 7 
p = p + 2; a
#include <stdio.h> 
The above line is interpreted as
10 100
int main() 
p = p + 2 * sizeof(data type) 0
{ 20 100
int a[] = {10, 20, 30, 40, 50};  4
Here, the array is of int type , 30 100
int *p = a; so 8
40 101
p = p + 2; 
p = p + 2 * sizeof(int) 2
50 101
return 0; 
p=p+2*4 6
}

p=p+8

Here p = 1000 so p


p = 1000 + 8 1008 200
0

p = 1008

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
Rules
Example Code 7 
p = p + 3; a
#include <stdio.h> 
The above line is interpreted as
10 100
int main() 
p = p + 3 * sizeof(data type) 0
{ 20 100
int a[] = {10, 20, 30, 40, 50};  4
Here, the array is of int type , 30 100
int *p = a; so 8
40 101
p = p + 3; 
p = p + 3 * sizeof(int) 2
50 101
return 0; 
p=p+3*4 6
}

p = p + 12

Here p = 1000 so p


p = 1000 + 12 1012 200
0

p = 1012

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
Rules
Example Code 7 
p = p + 4; a
#include <stdio.h> 
The above line is interpreted as
10 100
int main() 
p = p + 4 * sizeof(data type) 0
{ 20 100
int a[] = {10, 20, 30, 40, 50};  4
Here, the array is of int type , 30 100
int *p = a; so 8
40 101
p = p + 4; 
p = p + 4 * sizeof(int) 2
50 101
return 0; 
p=p+4*4 6
}

p = p + 16

Here p = 1000 so p


p = 1000 + 16 1016 200
0

p = 1016

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
- Relationship with Array
Rules

p = p + 2;
a

As we know, above line is interpreted as
10 100

p = p + 2 * sizeof(int) 0
20 100

p=p+2*4 4
30 100 &a[2]

p = 1008 8
40 101

1008 → &a[2] 2
50 101
6

1008 200
0

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
- Relationship with Array
Rules

p = p + 2;
a

As we know, above line is interpreted as
10 100

p = p + 2 * sizeof(int) 0
20 100

p=p+2*4 4
a[2] 30 100 &a[2]

p = 1008 8
40 101

1008 → &a[2] 2
50 101

So 6

p + 2 → 1008 → &a[2]
p

*(p + 2) → *1008 → a[2]
1008 200

*(p + 2) → a[2] 0

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
- Relationship with Array
Rules

*(p + 2) → a[2]
a

So the above line can be written as
10 100

*(p + i) → a[i] 0
20 100

So a[i] of can be written as shown below 4
a[2] 30 100 &a[2]

a[i] → *(a + i) 8
40 101

And this means 2
50 101

*(p + i) → *(a + i) 6

Which results too
p

p=a
1008 200

So to summarize “int *p = a” is valid (as per 2 nd
0
Interpretation)

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 5 - Pointer Arithmetic
- Relationship with Array
Rules

Wait!!, Before we end this rule, can I write
a

*(p + i) → *(i + p)?
10 100

Yes 0
20 100

Then, I can write a[i] as i[a] too!, that is 4
a[2] 30 100 &a[2]

a[i] → i[a] 8
40 101

We can index the elements with both the methods 2
50 101

So to Summarize 6


Rule: “Value(p + i) = Value(p) + i * sizeof(*p)”
p

The compiler does it for convenience
1008 200
0

Restricted Circulation | L&T Technology Services | www.LTTS.com


Restricted Circulation | L&T Technology Services | www.LTTS.com
Pointers - 7 Rules
Pointing to Nothing

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7
Rules

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 6 - Pointing to Nothing
Rules

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 6 - Pointing to Nothing
Rules
Sample Code 
Where is p pointing to?
#include <stdio.h> 
What does it Contain?
int main() 
Can you read or write wherever it is
{
int *p; pointing too?

So in summary where should p point? to
return 0;
}
avoid all these questions if we don’t have
a valid address yet?
p
100 ? ?

The answer is Point to Nothing!!
0 ?
?
? ?
?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 6 - Pointing to Nothing
Rules
Sample Code 
Now how do we Point to Nothing?
#include <stdio.h>

Well its a permitted location in the
int main() system will always give predictable
{ result!
int *p;

So it’s an act of initializing pointers to 0
return 0; (generally, implementation dependent)
} at definition.
p
100 ? ?
0 ?
?
? ?
?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 6 - Pointing to Nothing
Rules
Sample Code 
Now how do we Point to Nothing?
#include <stdio.h>

Well its a permitted location in the
int main() system will always give predictable
{ result!
int *p = 0;

So it’s an act of initializing pointers to 0
return 0; (generally, implementation dependent)
} at definition.
p
100 0 ?
0 ?
?
?
((void *) (0))
0 ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 6 - Pointing to Nothing
Rules
Sample Code 
If a pointer is initialized with null pointer
#include <stdio.h> constant, it is called null pointer

int main() 
A Null Pointer is logically understood to
{ be Pointing to Nothing
int *p = NULL;

De-referencing a NULL pointer is illegal
return 0; and will lead to crash (segment violation
} on Linux or reboot on custom board),
p which is better than pointing to some
100 NULL ? unknown location and failing randomly!
0 ?
?
?
#define NULL ((void *) (0))
NUL ? (Note: this is Implementation dependent)
L

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 6 - Pointing to Nothing
Rules

Rule: “Pointer value of NULL or Zero = Null Addr = Null Pointer = Pointing to
Nothing”

Restricted Circulation | L&T Technology Services | www.LTTS.com


To be Continued ...

Restricted Circulation | L&T Technology Services | www.LTTS.com


Restricted Circulation | L&T Technology Services | www.LTTS.com
Pointers - 7 Rules
Static vs Dynamic Allocation

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Static vs Dynamic Allocation
Rules

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Static vs Dynamic Allocation
Rules
Sample Code
#include <stdio.h>

int main()
{
int a[5];
int *p = malloc(5 * sizeof(int));

/* Need error handling and free */

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Static vs Dynamic Allocation
Rules
Sample Code a
2000 ? Static
#include <stdio.h>
Allocation

Named
2004 ?
int main() region
2008 ?
{
2012 ?
int a[5];
2016 ?
int *p = malloc(5 * sizeof(int));

/* Need error handling and free */

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Static vs Dynamic Allocation
Rules
Sample Code a
2000 ? Static
#include <stdio.h>
Allocation

Named
2004 ?
int main() region
2008 ?
{
2012 ?
int a[5];
2016 ?
int *p = malloc(5 * sizeof(int));

/* Need error handling and free */

return 0; Dynamic
1016 ?
} Allocation
1012 ?

Unnamed
Region
1008 ?
p 1004 ?
4000 1000 1000 ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Static vs Dynamic Allocation
Rules
Sample Code a
2000 ? Static
#include <stdio.h>
Allocation

Named
2004 ?
int main()  region
Managed by
2008 ?
{ compiler

Allocates the need memory
2012 ?
int a[5]; internally
2016 ?

Done while defining the
int *p = malloc(5 * sizeof(int));
variables
/* Need error handling and free */

return 0; Dynamic
1016 ?
} Allocation
1012 ?

Unnamed
 Region by
Managed
1008 ?
user
Allocate and de-allocates as
p 1004 ?

 needed
Done at run time using malloc &
4000 1000 1000 ?
free

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Static vs Dynamic Allocation
- Variable Length
Rules Array?
Sample Code Sample Code
#include <stdio.h> #include <stdio.h>

int main() int main()


{ {
int size; int size;

scanf(“%d”, &size); scanf(“%d”, &size);


int a[size]; int *p = malloc(size * sizeof(int));

return 0; int *p = realloc(p, 10 * sizeof(int));


} int *p = realloc(p, 2 * sizeof(int));

/* Need error handling and free */

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- The Need
Rules

You can decide the memory at run time

You can resize it as needed or whenever needed

You can decide when to create it and destroy it

You can request larger chunk of memory from the kernel

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- malloc()
Rules
Prototype
void *malloc(size_t size);


Allocate the memory from heap, the size requested is in bytes

On success it returns the allocated memory else NULL

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- malloc()
Rules
Used by other
Example Code 8 applications

#include <stdio.h> Free Bytes


#include <stdlib.h> ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); ?
?
if (p == NULL)
printf(“No Mem Available\n”);
?
?
/* Use the memory as needed */ 500 ?
?
free(p);
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- malloc()
Rules
Used by other
Example Code 8 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 ? ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); ?
?
if (p == NULL)
printf(“No Mem Available\n”);
?
?
/* Use the memory as needed */ 500 ?
?
free(p);
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- malloc()
Rules
Used by other
Example Code 8 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 500 ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); ?
?
if (p == NULL)
printf(“No Mem Available\n”);
?
?
/* Use the memory as needed */ 500 ?
?
free(p);
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- malloc()
Rules
Used by other
Example Code 8 applications

#include <stdio.h> Free Bytes


#include <stdlib.h> ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(15 * sizeof(char)); ?
?
if (p == NULL)
printf(“No Mem Available\n”);
?
?
/* Use the memory as needed */ 500 ?
?
free(p);
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- malloc()
Rules
Used by other
Example Code 8 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 ? ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(15 * sizeof(char)); ?
?
if (p == NULL)
printf(“No Mem Available\n”);
?
?
/* Use the memory as needed */ 500 ?
?
free(p);
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- malloc()
Rules
Used by other
Example Code 8 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 NULL ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(15 * sizeof(char)); ?
?
if (p == NULL)
printf(“No Mem Available\n”);
?
?
/* Use the memory as needed */ ?
?
free(p);
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- calloc()
Rules
Prototype
void *calloc(size_t nmemb, size_t size);


Allocate the memory from heap, the size requested is in bytes x
number of memory blocks needed

The allocated memory is filled with 0’s

On success it returns address of the allocated memory else
NULL

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- calloc()
Rules
Used by other
Example Code 9 applications

#include <stdio.h> Free Bytes


#include <stdlib.h> ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = calloc(5, sizeof(char)); ?
?
if (p == NULL)
printf(“No Mem Available\n”);
?
?
/* Use the memory as needed */ 500 ?
?
free(p);
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- calloc()
Rules
Used by other
Example Code 9 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 ? ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = calloc(5, sizeof(char)); ?
?
if (p == NULL)
printf(“No Mem Available\n”);
?
?
/* Use the memory as needed */ 500 ?
?
free(p);
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- calloc()
Rules
Used by other
Example Code 9 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 500 ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = calloc(5, sizeof(char)); 0
0
if (p == NULL)
printf(“No Mem Available\n”);
0
0
/* Use the memory as needed */ 500 0
?
free(p);
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- calloc()
Rules
Used by other
Example Code 9 applications

#include <stdio.h> Free Bytes


#include <stdlib.h> ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = calloc(15, sizeof(char)); ?
?
if (p == NULL)
printf(“No Mem Available\n”);
?
?
/* Use the memory as needed */ 500 ?
?
free(p);
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- calloc()
Rules
Used by other
Example Code 9 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 ? ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = calloc(15, sizeof(char)); ?
?
if (p == NULL)
printf(“No Mem Available\n”);
?
?
/* Use the memory as needed */ 500 ?
?
free(p);
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- calloc()
Rules
Used by other
Example Code 9 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 NULL ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = calloc(15, sizeof(char)); ?
?
if (p == NULL)
printf(“No Mem Available\n”);
?
?
/* Use the memory as needed */ 500 ?
?
free(p);
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- realloc()
Rules
Prototype
void *realloc(void *ptr, size_t size);


Modifies the size of an already allocated memory either by malloc or
calloc

On success it returns address of the allocated memory else
NULL

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- realloc()
Rules
Used by other
Example Code 10 applications

// Include Necessary header files ? Free Bytes


? Allocate Bytes
int main() ? by our Application
{ ?
char *p = malloc(4 * sizeof(char)); ?
NULL
// Say we wrote 1 to 4 in the Memory
?
p = realloc(p, 2 * sizeof(char));
?
p = realloc(p, 5 * sizeof(char));
?
// Say we wrote 3 to 5 in the Memory
507 ?
p = realloc(p, 8 * sizeof(char));
?
?
p = realloc(p, 25 * sizeof(char));
?
free(p); ?
return 0; ?
} 500 ?
?

NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- realloc()
Rules
Used by other
Example Code 10 p applications

// Include Necessary header files ? Free Bytes


4000 500
? Allocate Bytes
int main() ? by our Application
{ ?
char *p = malloc(4 * sizeof(char)); ?
NULL
// Say we wrote 1 to 4 in the Memory
?
p = realloc(p, 2 * sizeof(char));
?
p = realloc(p, 5 * sizeof(char));
?
// Say we wrote 3 to 5 in the Memory
507 ?
p = realloc(p, 8 * sizeof(char));
?
?
p = realloc(p, 25 * sizeof(char));
?
free(p); ?
return 0; ?
} 500 ?
?

NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- realloc()
Rules
Used by other
Example Code 10 p applications

// Include Necessary header files ? Free Bytes


4000 500
? Allocate Bytes
int main() ? by our Application
{ ?
char *p = malloc(4 * sizeof(char)); ?
NULL
// Say we wrote 1 to 4 in the Memory
?
p = realloc(p, 2 * sizeof(char));
?
p = realloc(p, 5 * sizeof(char));
?
// Say we wrote 3 to 5 in the Memory
507 ?
p = realloc(p, 8 * sizeof(char));
?
?
p = realloc(p, 25 * sizeof(char));
4
free(p); 3
return 0; 2
} 500 1
?

NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- realloc()
Rules
Used by other
Example Code 10 p applications

// Include Necessary header files ? Free Bytes


4000 500
? Allocate Bytes
int main() ? by our Application
{ ?
char *p = malloc(4 * sizeof(char)); ?
NULL
// Say we wrote 1 to 4 in the Memory
?
p = realloc(p, 2 * sizeof(char));
?
p = realloc(p, 5 * sizeof(char));
?
// Say we wrote 3 to 5 in the Memory
507 ?
p = realloc(p, 8 * sizeof(char));
?
?
p = realloc(p, 25 * sizeof(char));
4
free(p); ?
return 0; 2
} 500 1
?

NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- realloc()
Rules
Used by other
Example Code 10 p applications

// Include Necessary header files ? Free Bytes


4000 500
? Allocate Bytes
int main() ? by our Application
{ ?
char *p = malloc(4 * sizeof(char)); ?
NULL
// Say we wrote 1 to 4 in the Memory
?
p = realloc(p, 2 * sizeof(char));
?
p = realloc(p, 5 * sizeof(char));
?
// Say we wrote 3 to 5 in the Memory
507 ?
p = realloc(p, 8 * sizeof(char));
?
?
p = realloc(p, 25 * sizeof(char));
4
free(p); ?
return 0; 2
} 500 1
?

NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- realloc()
Rules
Used by other
Example Code 10 p applications

// Include Necessary header files ? Free Bytes


4000 500
? Allocate Bytes
int main() ? by our Application
{ ?
char *p = malloc(4 * sizeof(char)); ?
NULL
// Say we wrote 1 to 4 in the Memory
?
p = realloc(p, 2 * sizeof(char));
?
p = realloc(p, 5 * sizeof(char));
?
// Say we wrote 3 to 5 in the Memory
507 ?
p = realloc(p, 8 * sizeof(char));
?
5
p = realloc(p, 25 * sizeof(char));
4
free(p); 3
return 0; 2
} 500 1
?

NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- realloc()
Rules
Used by other
Example Code 10 p applications

// Include Necessary header files ? Free Bytes


4000 507
? Allocate Bytes
int main() ? by our Application
{ ?
char *p = malloc(4 * sizeof(char)); 5
NULL
// Say we wrote 1 to 4 in the Memory
4
p = realloc(p, 2 * sizeof(char));
3
p = realloc(p, 5 * sizeof(char));
2
// Say we wrote 3 to 5 in the Memory
507 1
p = realloc(p, 8 * sizeof(char));
?
?
p = realloc(p, 25 * sizeof(char));
4
free(p); 3
return 0; ?
} 500 1
?

NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- realloc()
Rules
Used by other
Example Code 10 p applications

// Include Necessary header files ? Free Bytes


4000 NULL
? Allocate Bytes
int main() ? by our Application
{ ?
char *p = malloc(4 * sizeof(char)); 5
NULL
// Say we wrote 1 to 4 in the Memory
4
p = realloc(p, 2 * sizeof(char));
3
p = realloc(p, 5 * sizeof(char));
2
// Say we wrote 3 to 5 in the Memory
507 1
p = realloc(p, 8 * sizeof(char));
?
?
p = realloc(p, 25 * sizeof(char));
4
free(p); 3
return 0; ?
} 500 1
?

NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- realloc()
Rules
Used by other
Example Code 10 p applications

// Include Necessary header files ? Free Bytes


4000 507
? Allocate Bytes
int main() ? by our Application
{ ?
char *p = malloc(4 * sizeof(char)); 5
NULL
// Say we wrote 1 to 4 in the Memory
4
p = realloc(p, 2 * sizeof(char));
3
p = realloc(p, 5 * sizeof(char));
2
// Say we wrote 3 to 5 in the Memory
507 1
p = realloc(p, 8 * sizeof(char));
?
?
char *pb = realloc(p, 25 * sizeof(char));
if (pb != NULL) { 4
p = pb; 3
pb = NULL; ?
} 500 1
?
free(p);
NULL ?
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- realloc()
Rules
Used by other
Example Code 10 p applications

// Include Necessary header files ? Free Bytes


4000 507
? Allocate Bytes
int main() ?
pb by our Application
{ ?
char *p = malloc(4 * sizeof(char)); NULL
4008 NULL 5
// Say we wrote 1 to 4 in the Memory
4
p = realloc(p, 2 * sizeof(char));
3
p = realloc(p, 5 * sizeof(char));
2
// Say we wrote 3 to 5 in the Memory
507 1
p = realloc(p, 8 * sizeof(char));
?
?
char *pb = realloc(p, 25 * sizeof(char));
if (pb != NULL) { 4
p = pb; 3
pb = NULL; ?
} 500 1
?
free(p);
NULL ?
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- free()
Rules
Prototype
void free(void *ptr);


Free the memory which should have allocated with the help of malloc(),
calloc() or realloc()

Freeing an already released block or any other block may have
undefined behavior

Freeing NULL doesn’t have any effect

If free is called with invalid argument, it may collapse the memory
management system

If free is not called after dynamic memory allocation, it will lead to
memory leak

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- free()
Rules
Used by other
Example Code 11 applications

#include <stdio.h> Free Bytes


#include <stdlib.h> ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); ?
/* TODO: Error handling */ ?
for (int i = 0; i < 5; i++)
?
p[i] = i + ‘A’; ?
500 ?
free(p);
?
p = NULL;
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- free()
Rules
Used by other
Example Code 11 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 ? ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); ?
/* TODO: Error handling */ ?
for (int i = 0; i < 5; i++)
?
p[i] = i + ‘A’; ?
500 ?
free(p);
?
p = NULL;
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- free()
Rules
Used by other
Example Code 11 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 500 ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); ?
/* TODO: Error handling */ ?
for (int i = 0; i < 5; i++)
?
p[i] = i + ‘A’; ?
500 ?
free(p);
?
p = NULL;
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- free()
Rules
Used by other
Example Code 11 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 500 ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); E
/* TODO: Error handling */ D
for (int i = 0; i < 5; i++)
C
p[i] = i + ‘A’; B
500 A
free(p);
?
p = NULL;
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- free()
Rules
Used by other
Example Code 11 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 500 ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); E
/* TODO: Error handling */ D
for (int i = 0; i < 5; i++)
C
p[i] = i + ‘A’; B
500 A
free(p);
?
p = NULL;
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 7 - Dynamic Allocation
- free()
Rules
Used by other
Example Code 11 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 NULL ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); E
/* TODO: Error handling */ D
for (int i = 0; i < 5; i++)
C
p[i] = i + ‘A’; B
500 A
free(p);
?
p = NULL;
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7
Rules

Pointer is an Integer

Referencing and De-referencing

Pointer means containing

Pointer Types

Pointer Arithmetic

Pointing to Nothing

Static vs Dynamic Allocation

Restricted Circulation | L&T Technology Services | www.LTTS.com


Restricted Circulation | L&T Technology Services | www.LTTS.com
Void Pointers

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - 7 - Rule 6 - Pointing to Nothing
Rules
Sample Code 
If a pointer is initialized with null pointer
#include <stdio.h> constant, it is called null pointer

int main() 
A Null Pointer is logically understood to
{ be Pointing to Nothing
int *p = NULL;

De-referencing a NULL pointer is illegal
return 0; and will lead to crash (segment violation
} on Linux or reboot on custom board),
p which is better than pointing to some
100 NULL ? unknown location and failing randomly!
0 ?
?
?
#define NULL ((void *) (0))
NUL ? (Note: this is Implementation dependent)
L

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void Pointers

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void
Pointers

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void
Pointers
Sample Code char
#include <stdio.h> 1000 ?
#include <stdlib.h> p1
4000 1000
int main() short
{ 1002 ?
char *p1; p2
short *p2;
int *p3; 4008 1002
float *p4; int
1004 ?
return 0; p3
}
4016 1004
float
1008 ?
p4
4024 1008

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void
Pointers
Sample Code
#include <stdio.h>
#include <stdlib.h>

int main() Generic


{ data!!
1002 ?
char *p1; p
short *p2;
int *p3; 4008 1002
float *p4;
*p; // How to point to generic data!!?

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void
Pointers
Sample Code
#include <stdio.h>
#include <stdlib.h>

int main() Array of Shorts


{ 1002 ?
char *p1; p
?
short *p2;
int *p3; 4008 1002 ?
float *p4; ?
*p; // How to point to generic data!!?

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void
Pointers
Sample Code
#include <stdio.h>
#include <stdlib.h>

int main() Array of


{ Doubles
1002 ?
char *p1; p
?
short *p2;
int *p3; 4008 1002 ?
float *p4; ?
*p; // How to point to generic data!!?

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void Pointers


A pointer to generic data!! which can be used the way we want, since it
doesn’t have types attached to it

Since its a incomplete type, the following has to be taken care

It can’t be de-referenced!!. We must type cast to de-reference

Pointer arithmetic cannot be performed (Compiler support needed)

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void Pointers

:GCC Extension:
6.22 Arithmetic on void- and Function-Pointers

In GNU C, addition and subtraction operations are supported on pointers to void and on
pointers to functions. This is done by treating the size of a void or a function as 1.

A consequence of this is that sizeof is also allowed on void and on function types, and
returns 1.

The option -Wpointer-arith requests a warning if these extensions are used

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void Pointers

Example Code 12
#include <stdio.h>

int main()
{
int a[] = {0x12345678, 0xABCDE987};
void *vp = a;

printf(“%hhx\n”, *(char *)vp);


printf(“%hhx\n”, *(char *)(vp + 7));
printf(“%hx\n”, *(short *)(vp + 3));
printf(“%x\n”, *(int *)(vp + 2));

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void Pointers

Example Code 12
a
#include <stdio.h>
78 1000
int main() 56 1001
{
int a[] = {0x12345678, 0xABCDE987}; 34 1002
void *vp = a;
12 1003
printf(“%hhx\n”, *(char *)vp); 87 1004
printf(“%hhx\n”, *(char *)(vp + 7));
printf(“%hx\n”, *(short *)(vp + 3)); E9 1005
printf(“%x\n”, *(int *)(vp + 2)); CD 1006

return 0; AB 1007
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void Pointers

Example Code 12
a vp
#include <stdio.h>
78 100 1000 200
int main() 0 0
56 1001
{
int a[] = {0x12345678, 0xABCDE987}; 34 1002
void *vp = a;
12 1003
printf(“%hhx\n”, *(char *)vp); 87 1004
printf(“%hhx\n”, *(char *)(vp + 7));
printf(“%hx\n”, *(short *)(vp + 3)); E9 1005
printf(“%x\n”, *(int *)(vp + 2)); CD 1006

return 0; AB 1007
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void Pointers

Example Code 12
a vp
#include <stdio.h>
78 100 1000 200
int main() 0 + 0
56 1001
{ 0
int a[] = {0x12345678, 0xABCDE987}; 34 1002
void *vp = a;
12 1003
printf(“%hhx\n”, *(char *)vp); 87 1004
printf(“%hhx\n”, *(char *)(vp + 7));
printf(“%hx\n”, *(short *)(vp + 3)); E9 1005
printf(“%x\n”, *(int *)(vp + 2)); CD 1006

return 0; AB 1007
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void Pointers

Example Code 12
a vp
#include <stdio.h>
78 100 1000 200
int main() 0 + 0
56 1001
{ 7
int a[] = {0x12345678, 0xABCDE987}; 34 1002
void *vp = a;
12 1003
printf(“%hhx\n”, *(char *)vp); 87 1004
printf(“%hhx\n”, *(char *)(vp + 7));
printf(“%hx\n”, *(short *)(vp + 3)); E9 1005
printf(“%x\n”, *(int *)(vp + 2)); CD 1006

return 0; AB 1007
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void Pointers

Example Code 12
a vp
#include <stdio.h>
78 100 1000 200
int main() 0 + 0
56 1001
{ 3
int a[] = {0x12345678, 0xABCDE987}; 34 1002
void *vp = a;
12 1003
printf(“%hhx\n”, *(char *)vp); 87 1004
printf(“%hhx\n”, *(char *)(vp + 7));
printf(“%hx\n”, *(short *)(vp + 3)); E9 1005
printf(“%x\n”, *(int *)(vp + 2)); CD 1006

return 0; AB 1007
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void Pointers

Example Code 12
a vp
#include <stdio.h>
78 100 1000 200
int main() 0 + 0
56 1001
{ 2
int a[] = {0x12345678, 0xABCDE987}; 34 1002
void *vp = a;
12 1003
printf(“%hhx\n”, *(char *)vp); 87 1004
printf(“%hhx\n”, *(char *)(vp + 7));
printf(“%hx\n”, *(short *)(vp + 3)); E9 1005
printf(“%x\n”, *(int *)(vp + 2)); CD 1006

return 0; AB 1007
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Void Pointers

Example Code 12
a vp
#include <stdio.h>
78 100 1000 200
int main() 0 0
56 1001
{
int a[] = {0x12345678, 0xABCDE987}; 34 1002
char *vp = a; // Compiler Warning!!
12 1003
printf(“%hhx\n”, *(char *)vp); 87 1004
printf(“%hhx\n”, *(char *)(vp + 7));
printf(“%hx\n”, *(short *)(vp + 3)); E9 1005
printf(“%x\n”, *(int *)(vp + 2)); CD 1006

return 0; AB 1007
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Restricted Circulation | L&T Technology Services | www.LTTS.com
Constant Pointers

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant


Before we talk about the const qualifier along with pointers lets talk
about the values its deals with

A pointer deals with 2 values

Its own value, which is an address of another location

The value at the location its point in to

Pointer Data
Location
200 1000 100 10
0 Pointer own
0 Value at the
value, which location it’s
Is address Pointing to

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant


So it is possible that we sometimes have situations like

We want both variable

We want its value to be constant

We want the value at the location its pointing to, to be constant

At time both constants

Pointer Data
Location
200 1000 100 10
0 0
variabl variabl
e
constan e
variabl
tvariable e
constan
constan tconstan
t t

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant


So, we may have to define pointers as per the above needs, and this is
the place where the constant qualifier comes in picture

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 13 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main()
{
int a[] = {10, 20};
int *p = a;

*p = 100;
p++;
*p = 200;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 13 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Data


{ Location
int a[] = {10, 20}; a
int *p = a; 100 10
0 20
*p = 100; 100
p++; 4 Value at the
*p = 200; location it’s
pointing to
is a
return 0; Variable
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 13 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Pointer Data


{ Location
int a[] = {10, 20}; p a
int *p = a; 200 1000 100 10
0 0 20
*p = 100; Pointer own 100
p++; value, which 4 Value at the
Is address is
*p = 200; a location it’s
pointing to
Variable is a
return 0; Variable
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 13 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Pointer Data


{ Location
int a[] = {10, 20}; p a
int *p = a; 200 1000 100 100
0 0 20
*p = 100; Pointer own 100
p++; value, which 4 Value at the
Is address is
*p = 200; a location it’s
pointing to
Variable is a
return 0; Variable
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 13 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Pointer Data


{ Location
int a[] = {10, 20}; p a
int *p = a; 200 1004 100 100
0 0 20
*p = 100; Pointer own 100
p++; value, which 4 Value at the
Is address is
*p = 200; a location it’s
pointing to
Variable is a
return 0; Variable
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 13 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Pointer Data


{ Location
int a[] = {10, 20}; p a
int *p = a; 200 1004 100 100
0 0
*p = 100; Pointer own 100 200
p++; value, which 4 Value at the
Is address is
*p = 200; a location it’s
pointing to
Variable is a
return 0; Variable
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 14 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main()
{
int a[] = {10, 20};
const int *p = a;

++p;
*p = 100;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 14 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Data


{ Location
int a[] = {10, 20}; a
const int *p = a; 100 10
0 20
++p; 100
*p = 100; 4

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 14 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Pointer Data


{ Location
int a[] = {10, 20}; p a
const int *p = a; 200 1000 100 10
0 0 20
++p; Pointer own 100
*p = 100; value, which 4 Value at the
Is address is
a location it’s
pointing to
return 0; Variable is seen as a
}
Constant

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 14 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Pointer Data


{ Location
int a[] = {10, 20}; p a
const int *p = a; 200 1004 100 10
0 0 20
++p; Pointer own 100
*p = 100; value, which 4 Value at the
Is address is
a location it’s
pointing to
return 0; Variable is seen as a
}
Constant

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 14 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Pointer Data


{ Location
int a[] = {10, 20}; p a
const int *p = a; 200 1004 100 10
0 0 20
++p; Pointer own 100
*p = 100; // Compiler Error!! value, which 4 Value at the
Is address is
a location it’s
pointing to
return 0; Variable is seen as a
}
Constant

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 15 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main()
{
int a[] = {10, 20};
int * const p = a;

*p = 100;
++p;
*p = 200;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 15 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Data


{ Location
int a[] = {10, 20}; a
int * const p = a; 100 10
0 20
*p = 100; 100
++p; 4
*p = 200;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 15 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Pointer Data


{ Location
int a[] = {10, 20}; p a
int * const p = a; 200 1000 100 10
0 0 20
*p = 100; Pointer own 100
++p; value, which 4 Value at the
is address is
*p = 200; a location it’s
pointing to
Constant is seen as a
return 0;
Variable
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 15 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Pointer Data


{ Location
int a[] = {10, 20}; p a
int * const p = a; 200 1000 100 100
0 0 20
*p = 100; Pointer own 100
++p; value, which 4 Value at the
Is address is
*p = 200; a location it’s
pointing to
Constant is seen as a
return 0;
Variable
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 15 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Pointer Data


{ Location
int a[] = {10, 20}; p a
int * const p = a; 200 1000 100 10
0 0 20
*p = 100; Pointer own 100
++p; // Compiler Error!! value, which 4 Value at the
Is address is
*p = 200; a location it’s
pointing to
Constant is seen as a
return 0;
Variable
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 16 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main()
{
int a[] = {10, 20};
const int * const p = a;

*p = 100;
++p;
*p = 200;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 16 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Data


{ Location
int a[] = {10, 20}; a
const int * const p = a; 100 10
0 20
*p = 100; 100
++p; 4
*p = 200;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 16 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Pointer Data


{ Location
int a[] = {10, 20}; p a
const int * const p = a; 200 1000 100 10
0 0 20
*p = 100; Pointer own 100
++p; value, which 4 Value at the
is address is
*p = 200; a location it’s
pointing to
Constant is seen as a
return 0;
Constant
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 16 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main() Pointer Data


{ Location
int a[] = {10, 20}; p a
const int * const p = a; 200 1000 100 10
0 0 20
*p = 100; // Compiler Error!! Pointer own 100
++p; value, which 4 Value at the
Is address is
*p = 200; a location it’s
pointing to
Constant is seen as a
return 0;
Constant
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant


So the possible combinations are

Both variable

Its value to be constant

Value at the location its pointing to, to be constant

Both constants

Pointer Data
Location
200 1000 100 10
0 0
variabl variabl
e
constan e
variabl
tvariable e
constan
constan tconstan
t t

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 17 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

int main()
{
const int a[] = {10, 20};
int *p = a; // Compiler Warning!!

*p = 100;
++p;
*p = 200;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Constant

Example Code 18 Note: The discussion is with respect to the


compilation behavior. Any diagram seen would
#include <stdio.h> discussed on the same aspect.

const int a[] = {10, 20};

int main()
{
int *p = a; // Compiler Warning!!

*p = 100; // Run Time Error!!


++p;
*p = 200;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointer to Pointer
int val;
Multi level pointers are not
int *p1 = &val; recommended by coding
int **p2 = &p1; standards!!

//val, *p1, **p2


//p1, &val, *p2
//p2, &p1

&&val
applicable? More details on:
 Pointer to Pointer
 Visualize Pointer to a Pointe
r

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers


Do’s and Don’ts

Pointer Arithmetic - Subtractions

Precedence and
Associativity

Pointer Conversions

Associated Errors with Pointers

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Do’s and Don't
Used by other
Example Code 19 applications

#include <stdio.h> Free Bytes


#include <stdlib.h> ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); ?
/* TODO: Error handling */ ?
p = p + 8;
?
p = p - 8; ?
500 ?
free(p);
?
p = NULL;
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Do’s and Don't
Used by other
Example Code 19 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 ? ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); ?
/* TODO: Error handling */ ?
p = p + 8;
?
p = p - 8; ?
500 ?
free(p);
?
p = NULL;
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Do’s and Don't
Used by other
Example Code 19 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 ? ?
? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); ?
/* TODO: Error handling */ ?
p = p + 8;
?
p = p - 8; ?
500 ?
free(p);
?
p = NULL;
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Do’s and Don't
Used by other
Example Code 19 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 ? ?
508 ? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); ?
/* TODO: Error handling */ ?
p = p + 8; // Possible, But illegal
?
p = p - 8; ?
500 ?
free(p);
?
p = NULL;
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Do’s and Don't
Used by other
Example Code 19 p applications

#include <stdio.h> Free Bytes


#include <stdlib.h>
4000 ? ?
508 ? Allocate Bytes
by our Application
int main() ?
{ NULL
?
char *p;
?
p = malloc(5 * sizeof(char)); ?
/* TODO: Error handling */ ?
p = p + 8; // Possible, But illegal
?
p = p - 8; ?
500 ?
free(p);
?
p = NULL;
?
return 0;
}
NULL ?

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Do’s and Don't

Example Code 20
#include <stdio.h>
#include <stdlib.h>

int main()
{
char *p;

p = malloc(5 * sizeof(char));
/* TODO: Error handling */

p = p * 8; // Compilation Error
p = p / 8; // Compilation Error

free(p);
p = NULL;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Do’s and Don't

Example Code 21
#include <stdio.h>
#include <stdlib.h>

int main()
{
char *p;

p = malloc(5 * sizeof(char));
/* TODO: Error handling */

p = p + p; // Compilation Error
p = p * p; // Compilation Error
p = p / p; // Compilation Error

free(p);
p = NULL;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Do’s and Don't

Example Code 22
#include <stdio.h>
#include <stdlib.h>

int main()
{
char *p;

p = malloc(5 * sizeof(char));
/* TODO: Error handling */

p = p - p;
// Possible, gives you the distance
// between 2 pointers, in this case
// it would NULL!!

free(p);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Arithmetic

Example Code 23
#include <stdio.h>

int main()
{
int a[] = {10, 20, 30, 40, 50};
int *p1 = &a[0];
int *p2 = &a[1];

printf(“%ld\n”, p1 – p2);
printf(“%ld\n”, p2 – p1);
p2 = p2 + 2;
printf(“%ld\n”, p2 - p1);
printf(“%ld\n”, p1 – p2);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Arithmetic

Example Code 23
#include <stdio.h>

int main() a Position


{
int a[] = {10, 20, 30, 40, 50};
int *p1 = &a[0]; 10 1
int *p2 = &a[1];
20 2
printf(“%ld\n”, p1 – p2);
printf(“%ld\n”, p2 – p1); 30 3
p2 = p2 + 2;
printf(“%ld\n”, p2 - p1); 40 4
printf(“%ld\n”, p1 – p2);
50 5
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Arithmetic

Example Code 23
#include <stdio.h>

int main() a Position


{ p1
int a[] = {10, 20, 30, 40, 50};
int *p1 = &a[0]; 200 1000 100 10 1
int *p2 = &a[1]; 0 0
100 20 2
printf(“%ld\n”, p1 – p2); 4
printf(“%ld\n”, p2 – p1); 100 30 3
p2 = p2 + 2; 8
printf(“%ld\n”, p2 - p1); 101 40 4
printf(“%ld\n”, p1 – p2); 2
101 50 5
return 0; 6
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Arithmetic

Example Code 23
#include <stdio.h>

int main() a Position


{ p1
int a[] = {10, 20, 30, 40, 50};
int *p1 = &a[0]; 200 1000 100 10 1
int *p2 = &a[1]; 0 0
p2 100 20 2
printf(“%ld\n”, p1 – p2); 4
printf(“%ld\n”, p2 – p1); 200 1004 100 30 3
p2 = p2 + 2; 8 8
printf(“%ld\n”, p2 - p1); 101 40 4
printf(“%ld\n”, p1 – p2); 2
101 50 5
return 0; 6
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Arithmetic

Example Code 23
#include <stdio.h>

int main() a Position


{ p1
int a[] = {10, 20, 30, 40, 50};
int *p1 = &a[0]; 200 1000 100 10 1
0 0 -1
int *p2 = &a[1];
p2 100 20 2
printf(“%ld\n”, p1 – p2); 4
printf(“%ld\n”, p2 – p1); 200 1004 100 30 3
p2 = p2 + 2; 8 8
printf(“%ld\n”, p2 - p1); 101 40 4
printf(“%ld\n”, p1 – p2); 2
101 50 5
return 0; 6
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Arithmetic

Example Code 23
#include <stdio.h>

int main() a Position


{ p1
int a[] = {10, 20, 30, 40, 50};
int *p1 = &a[0]; 200 1000 100 10 1
int *p2 = &a[1]; 0 0 1
p2 100 20 2
printf(“%ld\n”, p1 – p2); 4
printf(“%ld\n”, p2 – p1); 200 1004 100 30 3
p2 = p2 + 2; 8 8
printf(“%ld\n”, p2 - p1); 101 40 4
printf(“%ld\n”, p1 – p2); 2
101 50 5
return 0; 6
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Arithmetic

Example Code 23
#include <stdio.h>

int main() a Position


{ p1
int a[] = {10, 20, 30, 40, 50};
int *p1 = &a[0]; 200 1000 100 10 1
int *p2 = &a[1]; 0 0
p2 100 20 2
printf(“%ld\n”, p1 – p2); 4
printf(“%ld\n”, p2 – p1); 200 1012 100 30 3
p2 = p2 + 2; 8 8
printf(“%ld\n”, p2 - p1); 101 40 4
printf(“%ld\n”, p1 – p2); 2
101 50 5
return 0; 6
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Arithmetic

Example Code 23
#include <stdio.h>

int main() a Position


{ p1
int a[] = {10, 20, 30, 40, 50};
int *p1 = &a[0]; 200 1000 100 10 1
int *p2 = &a[1]; 0 0
p2 100 20 2
printf(“%ld\n”, p1 – p2); 4 3
printf(“%ld\n”, p2 – p1); 200 1012 100 30 3
p2 = p2 + 2; 8 8
printf(“%ld\n”, p2 - p1); 101 40 4
printf(“%ld\n”, p1 – p2); 2
101 50 5
return 0; 6
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Arithmetic

Example Code 23
#include <stdio.h>

int main() a Position


{ p1
int a[] = {10, 20, 30, 40, 50};
int *p1 = &a[0]; 200 1000 100 10 1
int *p2 = &a[1]; 0 0
p2 100 20 2
printf(“%ld\n”, p1 – p2); 4 -3
printf(“%ld\n”, p2 – p1); 200 1012 100 30 3
p2 = p2 + 2; 8 8
printf(“%ld\n”, p2 - p1); 101 40 4
printf(“%ld\n”, p1 – p2); 2
101 50 5
return 0; 6
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Precedence and
Associativity
Example Code 24
#include <stdio.h>

int main()
{
int a[] = {10, 20, 30, 40, 50};
int *p = &a[0];
Since the precedence level of the *
*p++; printf(“%ld\n”, *p);
operator and ++/-- operator are the
*(p++); printf(“%ld\n”, *p);
(*p)++; printf(“%ld\n”, *p); same, their associativity is from right
++*p; printf(“%ld\n”, *p); to left.
++(*p); printf(“%ld\n”, *p);
*++p; printf(“%ld\n”, *p);
*(++p); printf(“%ld\n”, *p);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Precedence and
Associativity
Example Code 24
#include <stdio.h>

int main() a
{
int a[] = {10, 20, 30, 40, 50};
int *p = &a[0];
100 10
0
*p++; printf(“%ld\n”, *p); 100 20
*(p++); printf(“%ld\n”, *p); 4
(*p)++; printf(“%ld\n”, *p); 100 30
++*p; printf(“%ld\n”, *p); 8
++(*p); printf(“%ld\n”, *p); 101 40
*++p; printf(“%ld\n”, *p); 2
*(++p); printf(“%ld\n”, *p); 101 50
6
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Precedence and
Associativity
Example Code 24
#include <stdio.h>

int main() a
{ p
int a[] = {10, 20, 30, 40, 50};
int *p = &a[0]; 200 1000 100 10
0 0
*p++; printf(“%ld\n”, *p); 100 20
*(p++); printf(“%ld\n”, *p); 4
(*p)++; printf(“%ld\n”, *p); 100 30
++*p; printf(“%ld\n”, *p); 8
++(*p); printf(“%ld\n”, *p); 101 40
*++p; printf(“%ld\n”, *p); 2
*(++p); printf(“%ld\n”, *p); 101 50
6
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Precedence and
Associativity
Example Code 24
#include <stdio.h>

int main() a
{ p
int a[] = {10, 20, 30, 40, 50};
int *p = &a[0]; 200 1004 100 10
0 0
*p++; printf(“%ld\n”, *p); 100 20
*(p++); printf(“%ld\n”, *p); 4
(*p)++; printf(“%ld\n”, *p); 100 30
++*p; printf(“%ld\n”, *p); 8
++(*p); printf(“%ld\n”, *p); 101 40
*++p; printf(“%ld\n”, *p); 2
*(++p); printf(“%ld\n”, *p); 101 50
6
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Precedence and
Associativity
Example Code 24
#include <stdio.h>

int main() a
{ p
int a[] = {10, 20, 30, 40, 50};
int *p = &a[0]; 200 1008 100 10
0 0
*p++; printf(“%ld\n”, *p); 100 20
*(p++); printf(“%ld\n”, *p); 4
(*p)++; printf(“%ld\n”, *p); 100 30
++*p; printf(“%ld\n”, *p); 8
++(*p); printf(“%ld\n”, *p); 101 40
*++p; printf(“%ld\n”, *p); 2
*(++p); printf(“%ld\n”, *p); 101 50
6
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Precedence and
Associativity
Example Code 24
#include <stdio.h>

int main() a
{ p
int a[] = {10, 20, 30, 40, 50};
int *p = &a[0]; 200 1008 100 10
0 0
*p++; printf(“%ld\n”, *p); 100 20
*(p++); printf(“%ld\n”, *p); 4
(*p)++; printf(“%ld\n”, *p); 100 31
++*p; printf(“%ld\n”, *p); 8
++(*p); printf(“%ld\n”, *p); 101 40
*++p; printf(“%ld\n”, *p); 2
*(++p); printf(“%ld\n”, *p); 101 50
6
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Precedence and
Associativity
Example Code 24
#include <stdio.h>

int main() a
{ p
int a[] = {10, 20, 30, 40, 50};
int *p = &a[0]; 200 1008 100 10
0 0
*p++; printf(“%ld\n”, *p); 100 20
*(p++); printf(“%ld\n”, *p); 4
(*p)++; printf(“%ld\n”, *p); 100 32
++*p; printf(“%ld\n”, *p); 8
++(*p); printf(“%ld\n”, *p); 101 40
*++p; printf(“%ld\n”, *p); 2
*(++p); printf(“%ld\n”, *p); 101 50
6
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Precedence and
Associativity
Example Code 24
#include <stdio.h>

int main() a
{ p
int a[] = {10, 20, 30, 40, 50};
int *p = &a[0]; 200 1008 100 10
0 0
*p++; printf(“%ld\n”, *p); 100 20
*(p++); printf(“%ld\n”, *p); 4
(*p)++; printf(“%ld\n”, *p); 100 33
++*p; printf(“%ld\n”, *p); 8
++(*p); printf(“%ld\n”, *p); 101 40
*++p; printf(“%ld\n”, *p); 2
*(++p); printf(“%ld\n”, *p); 101 50
6
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Precedence and
Associativity
Example Code 24
#include <stdio.h>

int main() a
{ p
int a[] = {10, 20, 30, 40, 50};
int *p = &a[0]; 200 1012 100 10
0 0
*p++; printf(“%ld\n”, *p); 100 20
*(p++); printf(“%ld\n”, *p); 4
(*p)++; printf(“%ld\n”, *p); 100 33
++*p; printf(“%ld\n”, *p); 8
++(*p); printf(“%ld\n”, *p); 101 40
*++p; printf(“%ld\n”, *p); 2
*(++p); printf(“%ld\n”, *p); 101 50
6
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Precedence and
Associativity
Example Code 24
#include <stdio.h>

int main() a
{ p
int a[] = {10, 20, 30, 40, 50};
int *p = &a[0]; 200 1016 100 10
0 0
*p++; printf(“%ld\n”, *p); 100 20
*(p++); printf(“%ld\n”, *p); 4
(*p)++; printf(“%ld\n”, *p); 100 33
++*p; printf(“%ld\n”, *p); 8
++(*p); printf(“%ld\n”, *p); 101 40
*++p; printf(“%ld\n”, *p); 2
*(++p); printf(“%ld\n”, *p); 101 50
6
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Conversions

Example Code 25
#include <stdio.h>

int main()
{
int x = 0x41424344;
float y = 3.2;
char *p1 = &x;
int *p2 = &y;

printf(“%c\n”, *p1);
printf(“%x\n”, *p2);
printf(“%hx\n”, *(short *) p2);
*(p1 + 3) = 0x31;
printf(“%x\n”, x);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Conversions

Example Code 25 x

#include <stdio.h> 44 43 42 41
int main() 100 100 100 100
{ 3 2 1 0
int x = 0x41424344;
float y = 3.2;
char *p1 = &x;
int *p2 = &y;

printf(“%c\n”, *p1);
printf(“%x\n”, *p2);
printf(“%hx\n”, *(short *) p2);
*(p1 + 3) = 0x31;
printf(“%x\n”, x);

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Conversions

Example Code 25 x

#include <stdio.h> 44 43 42 41
int main() 100 100 100 100
{ 3 2 1 0
int x = 0x41424344;
float y = 3.2;
char *p1 = &x;
int *p2 = &y;

printf(“%c\n”, *p1); y
printf(“%x\n”, *p2); NOTE: Value in
printf(“%hx\n”, *(short *) p2); 40 4C CC CD Hex

*(p1 + 3) = 0x31;
printf(“%x\n”, x);
100 100 100 100
7 6 5 4
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Conversions

Example Code 25 x

#include <stdio.h> 44 43 42 41
int main() 100 100 100 100
{ 3 2 1 0
int x = 0x41424344;
p1
float y = 3.2;
char *p1 = &x; // Warning
1000 200
int *p2 = &y;
0
printf(“%c\n”, *p1); y
printf(“%x\n”, *p2); NOTE: Value in
printf(“%hx\n”, *(short *) p2); 40 4C CC CD Hex

*(p1 + 3) = 0x31;
printf(“%x\n”, x);
100 100 100 100
7 6 5 4
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Conversions

Example Code 25 x

#include <stdio.h> 44 43 42 41
int main() 100 100 100 100
{ 3 2 1 0
int x = 0x41424344;
p1
float y = 3.2;
char *p1 = (char *) &x;
1000 200
int *p2 = (int *) &y;
0
printf(“%c\n”, *p1); y
printf(“%x\n”, *p2); NOTE: Value in
printf(“%hx\n”, *(short *) p2); 40 4C CC CD Hex

*(p1 + 3) = 0x31;
printf(“%x\n”, x);
100 100 100 100
7 6 5 4
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Conversions

Example Code 25 x

#include <stdio.h> 44 43 42 41
int main() 100 100 100 100
{ 3 2 1 0
int x = 0x41424344;
p1
float y = 3.2;
char *p1 = (char *) &x;
1000 200
int *p2 = (int *) &y;
0
printf(“%c\n”, *p1); y
printf(“%x\n”, *p2); NOTE: Value in
printf(“%hx\n”, *(short *) p2); 40 4C CC CD Hex

*(p1 + 3) = 0x31;
printf(“%x\n”, x);
100 100 100 100
7 6 5 4
return 0; p2
}
1004 200
8

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Conversions

Example Code 24 x

#include <stdio.h> 44 43 42 41
int main() 100 100 100 100
{ 3 2 1 0
int x = 0x41424344;
p1
float y = 3.2;
char *p1 = (char *) &x;
1000 200
int *p2 = (int *) &y;
0
printf(“%c\n”, *p1); y
printf(“%x\n”, *p2); NOTE: Value in
printf(“%hx\n”, *(short *) p2); 40 4C CC CD Hex

*(p1 + 3) = 0x31;
printf(“%x\n”, x);
100 100 100 100
7 6 5 4
return 0; p2
}
1004 200
8

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Conversions

Example Code 25 x

#include <stdio.h> 44 43 42 41
int main() 100 100 100 100
{ 3 2 1 0
int x = 0x41424344;
p1
float y = 3.2;
char *p1 = (char *) &x;
1000 200
int *p2 = (int *) &y;
0
printf(“%c\n”, *p1); y
printf(“%x\n”, *p2); NOTE: Value in
printf(“%hx\n”, *(short *) p2); 40 4C CC CD Hex

*(p1 + 3) = 0x31;
printf(“%x\n”, x);
100 100 100 100
7 6 5 4
return 0; p2
}
1004 200
8

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Conversions

Example Code 25 x

#include <stdio.h> 44 43 42 41
int main() 100 100 100 100
{ 3 2 1 0
int x = 0x41424344;
p1
float y = 3.2;
char *p1 = (char *) &x;
1000 200
int *p2 = (int *) &y;
0
printf(“%c\n”, *p1); y
printf(“%x\n”, *p2); NOTE: Value in
printf(“%hx\n”, *(short *) p2); 40 4C CC CD Hex

*(p1 + 3) = 0x31;
printf(“%x\n”, x);
100 100 100 100
7 6 5 4
return 0; p2
}
1004 200
8

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Conversions

Example Code 25 x

#include <stdio.h> 31 43 42 41
int main() 100 100 100 100
{ 3 2 1 0
int x = 0x41424344;
p1
float y = 3.2;
char *p1 = (char *) &x;
1000 200
int *p2 = (int *) &y;
0
printf(“%c\n”, *p1); y
printf(“%x\n”, *p2); NOTE: Value in
printf(“%hx\n”, *(short *) p2); 40 4C CC CD Hex

*(p1 + 3) = 0x31;
printf(“%x\n”, x);
100 100 100 100
7 6 5 4
return 0; p2
}
1004 200
8

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Conversions

Example Code 25 x

#include <stdio.h> 31 43 42 41
int main() 100 100 100 100
{ 3 2 1 0
int x = 0x41424344;
p1
float y = 3.2;
char *p1 = (char *) &x;
1000 200
int *p2 = (int *) &y;
0
printf(“%c\n”, *p1); y
printf(“%x\n”, *p2); NOTE: Value in
printf(“%hx\n”, *(short *) p2); 40 4C CC CD Hex

*(p1 + 3) = 0x31;
printf(“%x\n”, x);
100 100 100 100
7 6 5 4
return 0; p2
}
1004 200
8

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Pitfalls - Segmentation Fault

Example Code 26 Example Code 27 Example Code 28


#include <stdio.h> #include <stdio.h> #include <stdio.h>

int main() int main() int main()


{ { {
int x = 0; int *p = 0; int *p = 0;

printf(“Enter the number: ”); *p = 100; printf(“Enter the number: ”);


scanf(“%d”, x); scanf(“%d”, p);
return 0;
return 0; } return 0;
} }

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Pitfalls

Example Code 29
#include <stdio.h>

int main()
{
int *p1;
static int *p2;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Pitfalls

Example Code 29
#include <stdio.h>

int main()
{
int *p1; // Wild Pointer
static int *p2;

return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Pitfalls - Memory Leak

Example Code 30
#include <stdio.h>

int main()
{
int *p, size, sum;

while (1) {
scanf(“%d”, &size);
p = malloc(size * sizeof(int));

sum = 0;
for (i = 0; i < size; i++) {
scanf(“%d”, &p[i]);
sum = sum + p[i];
}

printf(“The sum of array elements are %d\n”, sum);


/* Forgot to free!! and the loop continues */
}
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Pitfalls - Memory Leak

Example Code 30
#include <stdio.h>

int main()
{
int *p, size, sum;

while (1) {
scanf(“%d”, &size); // 1st Cycle, Say user enters 10
p
p = malloc(size * sizeof(int));

sum = 0;
for (i = 0; i < size; i++) {
scanf(“%d”, &p[i]);
sum = sum + p[i];
}

printf(“The sum of array elements are %d\n”, sum);


/* Forgot to free!! and the loop continues */
}
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Pitfalls - Memory Leak

Example Code 30
#include <stdio.h>
Memor
int main() y
{ Leaked
int *p, size, sum;

while (1) {
scanf(“%d”, &size); // 2nd Cycle, Say user enters 5
p
p = malloc(size * sizeof(int));

sum = 0;
for (i = 0; i < size; i++) {
scanf(“%d”, &p[i]);
sum = sum + p[i];
}

printf(“The sum of array elements are %d\n”, sum);


/* Forgot to free!! and the loop continues */
}
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Pitfalls - Memory Leak

Example Code 30
#include <stdio.h>
Memor
int main() y
{ Leaked
int *p, size, sum;
Memor
while (1) { y
scanf(“%d”, &size); // 3rd Cycle, Say user enters 7 Leaked
p
p = malloc(size * sizeof(int));

sum = 0;
for (i = 0; i < size; i++) {
scanf(“%d”, &p[i]);
sum = sum + p[i];
}

printf(“The sum of array elements are %d\n”, sum);


/* Forgot to free!! and the loop continues */
}
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers - Pitfalls - Memory Leak

Example Code 30
#include <stdio.h>
Memor
int main() y
{ Leaked
int *p, size, sum;
Memor
while (1) { y
scanf(“%d”, &size); // nth Cycle, Say user enters 5 Leaked
p
p = malloc(size * sizeof(int));
Memor
sum = 0; y
Leaked
for (i = 0; i < size; i++) {
scanf(“%d”, &p[i]);
Memor
sum = sum + p[i]; y
} Leaked

printf(“The sum of array elements are %d\n”, sum);


/* Forgot to free!! and the loop continues */
}
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Thank You !

Restricted Circulation | L&T Technology Services | www.LTTS.com


Applied C - Structures & Unions

Restricted Circulation | L&T Technology Services | www.LTTS.com


Outline
Structures Basics
Definition, Variables, Simple I/O, Initialization
Memory layout – size and offset
Pointer Access
Structures and Functions
Pass By Value/Address, Efficient Method
Return by Value/Address, Safety & Efficiency?
Efficient Techniques - Avoid returning structures
Structures and Arrays
Array of Structure Variables, Initialization
Arrays within Structure, Initialization
Pointer based traversals
Bit Fields
Alignment Issues & Padding Bits
Unions, Some use cases
Nested, Self Referential Structures & Unions
Restricted Circulation | L&T Technology Services | www.LTTS.com
Structures – Recall Basics

Restricted Circulation | L&T Technology Services | www.LTTS.com


Structure Basics

struct Account {
struct Box {
int uid;
int length;  Encapsulation of Data
char name[20];
char breadth;
double balance;
int height;  Members can differ by type or
int age;
}; meaning
};
 Contiguous memory for all
members

 Significance of structures
 Variable creation, Member access  Minimize no.of parameters
while passing to functions
 Size of structures, layout of structures  Capture multiple results from
functions (passing structures
 Memory allocation – only when variables are created (No
by reference and filling them)
memory applicable for just declared struct variable)

Restricted Circulation | L&T Technology Services | www.LTTS.com


Simple Example

struct Account a1;


scanf("%d%s%d%lf", &a1.id, sizeof(struct Account)
a1.name, &a1.balance, &a1.age);
a1.balance += 100; sizeof(struct Box)
printf("%d,%s,%d,%lf", a1.id,
a1.name, a1.balance, a1.age);

struct Box b1;


scanf("%d%d%d",&b1.length, &b1.breadth, Avoid declaring structure
&b1.height); variables, at end of structure of
vol = b1.length * b1.breadth * b1.height; definition.
b1.height -= 1; Complete structure definition
and create variables in desired
printf("%d,%d,%d",b1.length, b1.breadth,
scope further
b1.height);

Restricted Circulation | L&T Technology Services | www.LTTS.com


Member Layout

1600-1635, size = 36 bytes

id name balance age

+0, 1600-1603 +4, 1604-1623 +24 , 1624-1631 +32 , 1632-1635

1500-1511, size = 12 bytes


Assumption :
length breadth height sizeof(int)=4 bytes
32 bit word size
+0, 1500-1503 +4, 1504-1507 +8 , 1508-1511

Restricted Circulation | L&T Technology Services | www.LTTS.com


Initialization

struct Account {
struct Box {
int uid;
int length;
char name[20];
char breadth; Structures
int age;
int height;
double balance;
};
};

struct Account a1 = { 1001, "Richard", 25, 5000 };


struct Account a2 = { 1002, "Stevens",30};
//a2.balance is initialized to zero
struct Account a3 = { 1003, "Torvalds" };
//age, balance are initialized to zero
struct Box b1 = { 10, 12, 5};
struct Box b2 = { 10 }; //breadth & height are initialized to zero
struct Box b3 = { }; //all are initialized to zero

Restricted Circulation | L&T Technology Services | www.LTTS.com


Structures and Pointers

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers to Structures

struct Box { struct Account {


int length; int id; Arrow
char breadth; char name[20]; operator
int height; double balance;
}; };

struct Account a1;


struct Box b1;
struct Account
struct Box *ptr;
*ptr; Pointer to Structure
ptr=&b1;
ptr=&a1;
//ptr->length
//ptr->id
//ptr->breadth
//ptr->name
//ptr->height
//ptr->balance

Restricted Circulation | L&T Technology Services | www.LTTS.com


Pointers to Structures
Code 1:

#include<stdio.h>

struct Box{
int length;
int breadth;
int height;
};

int main()
{
struct Box b1={10,20,2};
struct Box *ptr;
ptr=&b1;
printf("l=%d, b=%d, h=%d",ptr->length,ptr->breadth,ptr-
>height);
return 0;
}
Restricted Circulation | L&T Technology Services | www.LTTS.com
Self Referential Structure

• Self-Referential Structure contains one or more pointers pointing to


the structure of the same type.
• By using these pointers, an instance of the structure can be accessed
by another instance of the same structure.
• Structure pointing to themselves are called ‘Self-Referential’
structures.

Restricted Circulation | L&T Technology Services | www.LTTS.com


Self Referential Structure
Code 2:
#include<stdio.h>
struct self{
int length; ormal Structure l=10, b=20
int breadth; 2Self Referential Structure
struct self *ptr; l=30, b=40
};
int main() {
struct self a,b;
a.length=10;
a.breadth=20;
a.ptr=&b;
a.ptr->length=30;
a.ptr->breadth=40;
printf("Normal Structure l=%d, b=%d\n",a.length,a.breadth);
printf("Self Referential Structure l=%d, b=%d\
n",b.length,b.breadth);
return 0;
}
Restricted Circulation | L&T Technology Services | www.LTTS.com
Structures and Functions

Restricted Circulation | L&T Technology Services | www.LTTS.com


Parameter Passing – By Value
Code 3
main:-
int c; Is parameter
a
struct rectangle a; passing by value is
a.length=10; efficient, in case of l b
a.breadth=20; structures?
c=area(a);
printf("Area=%d",c); Copy Overhead

findVolume:-
int area(struct rectangle b) b
{ l b
return (b.length * b.breadth);
} Additional copy, user
defined data typically
large in size

Restricted Circulation | L&T Technology Services | www.LTTS.com


Parameter Passing – By Address
int c; Code 4  Efficient Parameter passing, avoids
main:-
struct rectangle a; additional copy of large structure
a.length=5; variables & copy overhead b1
a.breadth=20; l b h
 Const prefix for immutable
c=area(&a);
printf("Area= operations
%d",c);
No Copy Overhead

int area(struct rectangle *b)


{ findVolume:-
return (b->length * b->breadth);
}
ptr
No additional copy, just a
pointer irrespective of size
of structures

Restricted Circulation | L&T Technology Services | www.LTTS.com


Returning Structures – By Value/Address
Code 5 int main()
{
#include<stdio.h> int iArea; a
struct rectangle{ struct rectangle
l b a;h
int length; a=getValue();
int breadth; iArea =area(&a);
}; printf("Area =%d\n",
int area(struct rectangle *c) iArea);
{ l b h
return 0;
return (c->length * c->breadth); }
}
struct rectangle getValue() Main() Getvalue() Area()
{ Struct a Struct b Struct c
struct rectangle b;
printf("Enter length and breadth\
n"); Return type is not compatible with
scanf("%d%d",&b.length,&b.breadth); CPU registers!!
return b;
Pass Structures to Functions
} Restricted Circulation | L&T Technology Services | www.LTTS.com
Returning Structures – By Value/Address
Code 6:

struct rectangle *a;


a=getValue();
iArea=(a->length * a->breadth);
Printf(“Area=%d”,iArea);
struct rectangle* getValue()
{
struct rectangle b;
printf("Enter length and breadth\n");
scanf("%d%d",&b.length,&b.breadth);
return &b;
}

Is it safe?? Returning address of local variables, which will be destroyed when function
returns (Address to auto variable, in destroyed stack frame/activation record)

Restricted Circulation | L&T Technology Services | www.LTTS.com


Easy Solution
Code 6:

struct rectangle b; // Global Variable

struct rectangle *a;


a=getValue();
iArea=(a->length * a->breadth);
Printf(“Area=%d”,iArea);
struct rectangle* getValue()
{
printf("Enter length and breadth\
n");
scanf("%d
%d",&b.length,&b.breadth);
return &b;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Better Solution
Code 6a:

struct rectangle a;
getValue(&a);
iArea=(a.length * a.breadth);
Printf(“Area=%d”,iArea);

Void getValue(struct rectangle* a1)


{
printf("Enter length and breadth\n");
scanf("%d%d",&a1->length,&a1->breadth);
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Structures and Arrays

Restricted Circulation | L&T Technology Services | www.LTTS.com


Array of Structures
struct Trianee tarr[10];
struct Trainee {
for(int i=0;i<n;i++)
int tid;
scanf("%d%s%lf%d",&tarr[i].tid,
char name[20];
double score;
tarr[i].name,&tarr[i].score,&tarr[i].age);
int age;
};
for(int i=0;i<n;i++) {
printf("Id = %d\n",tarr[i].tid);
printf("Name = %d\n",tarr[i].name);
printf("Score = %lf\n",tarr[i].score);
printf("Age = %d\n",tarr[i].age);
}
struct Trainne *ptr=tarr;
for(int i=0;i<n;i++) {
total += ptr->score;
++ptr;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Initialization & Traversal
struct Trianee tarr[5] = {
{1001, "Richard", 76.23, 20
}, struct Trianee tarr[10];
{1002, "Stevens", 81.48, 22 struct Trainee *ptr=tarr;
}, for(int i=0;i<n;i++) {
{1003, "Lippman", 72.56, 21 scanf("%d%s%lf%d",&ptr->tid,
}, ptr->name, &ptr->score, &ptr-
{1004, "Ken", 64.15, 20 >age);
}, ++ptr;
{1005, "Thompson", 87.45, 24 }
},
};
struct Trianee tarr[10];
struct Trainee *ptr=tarr; struct Trianee tarr[10];
for(int i=0;i<n;i++) { struct Trainee *ptr=tarr;
printf("%d%s%lf%d", for(int i=0;i<n;i++) {
ptr->tid, ptr->name, display(ptr++); //display(&ptr[i]);
ptr->score, ptr->age); //total += (ptr++)->score;
++ptr; }
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Array within Structures
struct Trainee t1;
struct Trainee { scanf("%d%s%d",&t1.tid, t1.name,
int tid; &t1.age);
char name[20]; for(int j=0;j<5;j++)
double scores[5]; scanf("%d",&t1.scores[j]);
int age; for(int j=0;j<5;j++)
}; total += t1.scores[j];

struct Trainee t2 = { 1002, "Torvalds",


{72, 64, 84, 65, 60}, 25 };

Restricted Circulation | L&T Technology Services | www.LTTS.com


Combined Scenario
struct Trainee tarr[10];
for(int i=0;i<10;i++) {
scanf("%d%s%d",&tarr[i].tid,
tarr[i].name, &tarr[i].age);
for(int j=0;j<5;j++) Array of Structures
scanf("%d",
&tarr[i].scores[j]);
}
struct Trainee *ptr=tarr;
int total[10]={};
for(int i=0;i<10;i++) {
printf("%d%s%d",ptr->.tid, TODO:-
ptr->name, ptr->age);  Initialize the array of structures, with a array
for(int j=0;j<5;j++) member inside.
total[i] += ptr->scores[j];
//total[i] +=  Find module wise total from all trainees , i.e.
tarr[i].scores[j] scores[j] from all array elements
ptr++;
}
Restricted Circulation | L&T Technology Services | www.LTTS.com
Bit Fields

Restricted Circulation | L&T Technology Services | www.LTTS.com


Bit Fields

 Bit fields are applicable for integral


struct Sample { types only, more meaningfully for
unsigned int x : 2; unsigned types
unsigned int y : 5;
 Bit fields not applicable for float,
unsigned int : 3;
double types
unsigned int z : 4;
};  Address is not applicable for bit field
members, so offset also not
struct Sample s1; applicable
s1.x = 2;
s1.y = 23;  Name can be omitted for bit fields,
s1.z = 13; to leave some space in between

 A structure can have mix of bit fields Bit fields in structure


and normal members.

Restricted Circulation | L&T Technology Services | www.LTTS.com


I/O Mapping, Packing Examples
#define IOBASE 0x4200
#define IOBASE 0x4200
struct IPAddress {
unsigned int a : 8;
struct IODevice {
unsigned int b : 8;
unsigned int : 2;
unsigned int c : 8;
unsigned int status : 5;
unsigned int d : 8;
unsigned int wroff : 3;
};
unsigned int : 3;
unsigned int rdoff : 3
uint32_8 val = 0xC0A84819
};
struct IPAddress *ptr = &val;
struct IODevice *ptr;
ptr = (struct IODevice*)  Use bit fields sparingly, as bit level access is complex
(IOBASE);  Use bit fields for I/O Mapping, only when compiler
// ptr->status, ptr->rdoff conventions are very clear. (Direction of bit fields,
alignment, padding in between etc.)
 Bit fields vs Bitwise operators for I/O Mapping

Restricted Circulation | L&T Technology Services | www.LTTS.com


Unions

Restricted Circulation | L&T Technology Services | www.LTTS.com


Basic Concept & Example
union A {
int x; union B {
int y; int x;
int z; float y;
}; double z;
char ch;
union A a1; //char
a1.x=10; buf[32];
a1.y=20; };  Union is a space saving
//print a1.x, a1.y, encapsulation unit
a1.z
 All members will share same
memory

 Size of union is , max size of all


members
Union in C
 Offset of each union member is
zero

Restricted Circulation | L&T Technology Services | www.LTTS.com


Some use cases

union Sample {
uint32_t val;
union IPAddress {
struct Tuple {
uint32_t val;
uint8_t x;
struct IPPack {
uint8_t y;
unsigned int a : 8;
uint8_t z;
unsigned int b : 8;
}t1;
unsigned int c : 8;
uint8_t buf[8];
unsigned int d : 8;
};
}pack;
uint8_t carr[4];
struct Sensor {
};
enum SensorType type;
union IPAddress ip=0xC0A84819;
union Sample reading;
//access ip.carr[i] (or)
};
//ip.pack.a / b / c /d
//access reading.val, reading.buf
//(or) reading.t1 based on type

Restricted Circulation | L&T Technology Services | www.LTTS.com


Internals & Applied Concepts

Restricted Circulation | L&T Technology Services | www.LTTS.com


Designated Initializers – single Variable
struct Account a1 = { .uid=1001, .name="Scott",
struct Account {
int uid; .balance=6000, .age=20 };
char name[20]; struct Account a2 = {
double balance; .uid = 1001,
int age; .age = 25,
}; .name = "Thompson“
};

struct Box b1 =
struct Box {
{ .length=10, .breadth=12, .height=5 };
int length;
struct Box b2 = {
int breadth;
.length=12,
int height;
.height=10
};
};

Restricted Circulation | L&T Technology Services | www.LTTS.com


Designated Initializers – for Arrays

struct Trainee tarr[i] = {


struct Trainee {
{ .tid = 1001, .name="abc", .age=20 },
int tid;
{ .tid = 1002, .name="xyz", .age=22 },
char name[20];
{ .tid = 1003, .name="pqr", .age=21 },
double score;
{ .tid = 1004, .age=21, .name="lmn", },
int age;
{ 1005, "efgh", 0, 25 }
};
};

struct Trainee tarr[i] = {


[0] = { .tid = 1001, .name="abc", .age=20 int arr[100] = {
}, [25] = 300,
[3] = { .tid = 1004, .name="xyz", .age=22 [48] = 400
}, };
[2] = { 1003, "pqr", 0, 25 };
};

Restricted Circulation | L&T Technology Services | www.LTTS.com


Designated Initializers –Array within Structure
struct Trainee t1 = {
struct Trainee { .tid = 1001,
int tid; .name="abc",
char name[20]; .scores = {10,20,30,40,50};
double scores[5]; // { [0]=10,[3]=40
int age; }
}; .age=20
};
struct Trainee tarr[5] = {
{ .tid = 1001, .name="abc", .age=20,
.scores={10,20,30,40,50} },
//[0]
{ .tid = 1002, .name="xyz", .age=22,
.scores={10,20,30,40,50} },
//[1]
[4]= { 1005, "efgh", {10,20,30,40,50} , 25 }
};

Restricted Circulation | L&T Technology Services | www.LTTS.com


Aliasing with Typedef
typedef struct Account
Account; typedef struct { struct Sample{
typedef struct Account int id; int x;
account_t; uint32_t int y;
reading; int z;
typedef struct Box Box; enum Type type; }s1; //avoid
typedef struct Box box_t; }sensor_t; // }
s2={10,20,30};
typedef struct Box* typedef struct { struct {
boxPtr_t; uint8_t rval; uint8_t a;
typedef struct box_t* uint8_t gval; uint8_t b;
boxPtr_t; uint32_t bval; uint32_t c;
}color_t; }var; //avoid

Avoid declaring variables at end of structure


definition. Use tag name with struct keyword or
Anonymous structures , alias , to create variables in desires scope
aliasing with typedef

Restricted Circulation | L&T Technology Services | www.LTTS.com


Word Size Alignment & Padding Bits

What’s the size of these


struct B {
struct A { structures?
int x;  sizeof(struct A)
int x;
char c1;  sizeof(struct B) Possible
double y; definition of
double y;
float z; offsetof
float z; Analyze offset of each
char ch; macro!!
char c2; member using offsetof macro
}; available from stddef.h
};

Assumptions (32 bit env):-


 int size is 4 bytes
 word size is 4 bytes
offsetof(struct B, x); Size of structures and
offsetof(struct A, x);
offsetof(struct B, c1); TODO:- Analyze & compare offset of each member
offsetof(struct A, y);
offsetof(struct B, y); size of struct, offset of each will be aligned to word
offsetof(struct A, z);
offsetof(struct B, x); member in 32 bit & 64 bit size of target
offsetof(struct A, ch);
offsetof(struct B, c2); environment. architecture

Restricted Circulation | L&T Technology Services | www.LTTS.com


Padding Bits – between Array elements

Structure layout not aligned with word boundaries, no padding/slack bits

x x x x y y y y y y y y z z z z ch x x x x y y y y y y y y z z z

W0 W1 W2 W3 W4 W5 W6 W7

Structure layout aligned with word boundaries, with padding/slack bits

x x x x y y y y y y y y z z z z ch x x x x y y y y y y y y

W0 W1 W2 W3 W4 W5 W6 W7

Padding bits for better Alignment

Restricted Circulation | L&T Technology Services | www.LTTS.com


Padding Bits – between structure members

Structure layout without word alignment, no padding bits


struct B {
x x x x c1 y y y y y y y y z z z z c2 int x;
char c1;
double y;
float z;
W0 W1 W2 W3 W4 char c2;
};
Structure layout aligned with word boundaries, with padding/slack bits

x x x x c1 y y y y y y y y z z z z c2

Can we
minimize
W0 W1 W2 W3 W4 W5 padding bits?
Padding bits for better Alignment
Structure Padding

Restricted Circulation | L&T Technology Services | www.LTTS.com


To avoid Structure Padding
Using Pragma Using Attribute

Restricted Circulation | L&T Technology Services | www.LTTS.com


Nested Structures & Unions
struct Account {
struct Date {
int custId;
int dd;
char name[20];
int mm;
double balance;
int yy;
struct Date {
};
int dd;
struct Account {
int mm;
int custId;
int yy;
char name[20];
}dob;
double balance;
//struct Date
struct Date dob;
dob;
}
}
Analyze the following:-
 Structure inside structure
Inner structures has no significance unless a variable is  Union inside union
created from that structure. So we can define a structure  Union inside structure
outside, and create a variable in outer structure.  Structure inside union

Restricted Circulation | L&T Technology Services | www.LTTS.com


Self referential structures, forward declaration

struct Node {
int payload;
Self Referential Self Referential Structure
struct Node* pnext;
};
typedef struct Node node_t;

struct Node; //fwd


declaration
typedef struct {
typedef struct Node node_t;
int payload;
node_t *pnext; //error Fix
struct Node {
//node_t is incomplete
int payload;
}; //node_t is incomplete
node_t *pnext; //ok
};

Restricted Circulation | L&T Technology Services | www.LTTS.com


Restricted Circulation | L&T Technology Services | www.LTTS.com
Function Pointers

Restricted Circulation | L&T Technology Services | www.LTTS.com


Code 1
#include<stdio.h>

int multiply(int,int);
int multiply(int a,int b)
{
return a*b;
}

int main()
{
int (*ptr)(int,int)=&multiply;
int result=(*ptr)(5,6)
printf("Result=%d\n",result);
return 0;
}
Restricted Circulation | L&T Technology Services | www.LTTS.com
Passing Function Pointer as Function Arguments
Code 2
#include<stdio.h> float Gain(float a, float b)
int main() {
{ return a*b;
}
float (*fp)(float,float);
float Gain(float,float); void func(float (*funp)(float,float))
void func(float (*fp)(float,float)); {
float result; float func_result;
printf("\n Function func() is called ");
fp=Gain; func_result=(*funp)(10,2.1);
result=Gain(5,6.2); printf("\n Result of func() is %f",func_result);
printf("Result=%f\n",result); }
result=(*fp)(10,3.4);
Result=31.000000
printf("Result=%f\n",result); Result=34.000000
func(fp);
return 0; Function func() is called
Result of func() is 21.000000
} Restricted Circulation | L&T Technology Services | www.LTTS.com
Inline Function

Restricted Circulation | L&T Technology Services | www.LTTS.com


Inline

If the function definitions are really small, then inline keyword can be used at the time of function
declaration.

The effect of using inline is when that function call instruction is executed by the compiler,
compiler simply replaces that function call with the instructions written under the function.

By doing this ,compiler is eliminating the function call overhead, which reduces the execution
time

Restricted Circulation | L&T Technology Services | www.LTTS.com


Code-Inline.c
#include<stdio.h>
static inline int multiply(int a,int b)
{
return a*b;
}
int main()
{
printf("The result = %d",multiply(4,5));
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Command Line Arguments

Restricted Circulation | L&T Technology Services | www.LTTS.com


Inline
Arguments that are passed to main( ) function from the command line is called as
‘command line arguments’
main( ) function syntax should be declared using ‘argc’ and ‘argv’ arguments as shown
below:
Ex: int main(int argc, char *argv[])
‘argc’ stands for arguments count, It takes the integer count of character stream from
command line
2nd argument to main is *argv[],which is a character array listing all arguments to the
main( )
‘argv’ stands for Argument vector
If ‘argc’ value is one or greater than one, then there will be argc-1 argument vectors,
each represented as a pointer to a string
Always argv[0] will be name of the program
Restricted Circulation | L&T Technology Services | www.LTTS.com
Example 1

Restricted Circulation | L&T Technology Services | www.LTTS.com


Example 2

Restricted Circulation | L&T Technology Services | www.LTTS.com


Properties
These are arguments given to main( ) function
These arguments are given in run time while calling the executable
Last element of argv is NULL pointer (i.e argv[argc])
Starting from argv[1] we will have our command line arguments

Restricted Circulation | L&T Technology Services | www.LTTS.com


Arrays and Pointers

Restricted Circulation | L&T Technology Services | www.LTTS.com


Call by Value

Restricted Circulation | L&T Technology Services | www.LTTS.com


Call by Reference

Restricted Circulation | L&T Technology Services | www.LTTS.com


Call by Reference (Passing an Entire Array to a Function)

Restricted Circulation | L&T Technology Services | www.LTTS.com


Array of Pointers
A pointer variable always contains an address, an array of pointers would be a
collection of addresses of same type.
Ex: int *arr[10] – will contain the address of type int
The addresses present in the array can be addresses of individual variable or
address of array elements or any other addresses

Restricted Circulation | L&T Technology Services | www.LTTS.com


Array of Array

Restricted Circulation | L&T Technology Services | www.LTTS.com


Array of Array
include <stdio.h> printf("%p\n",a4[2]); for(i=0;i<3;i++)
int main() {
int *p=a4[i];
{ for (j=0;j<size[k];j++)
int i,j,k; {
int a1[]={1,2,3}; printf("%d\t",*p);
int a2[]={11,12,13,14,15}; p++;
int a3[]={51,52}; }
int *a4[3]; k++;
a4[0]=a1; printf("\n");
a4[1]=a2; }
a4[2]=a3; return 0;
int size[]={3,5,2}; 0x7fff7b6ed3fc
} 0x7fff7b6ed3e0
printf("%p\n",a4[0]); 0x7fff7b6ed3d8
printf("%p\n",a4[1]); Segmentation fault

Restricted Circulation | L&T Technology Services | www.LTTS.com


Strings

Restricted Circulation | L&T Technology Services | www.LTTS.com


Outline
• Creating Strings, passing strings to functions
• Library Functions to work on Strings
• Type conversions – String conversion library functions
• Building and Parsing Strings – sprint, sscanf etc.
• Raw Memory handling and String handling routines in the C standard library
• Arrays of Strings / Table of Strings – Fixed size vs variable length
• Command Line Arguments

Restricted Circulation | L&T Technology Services | www.LTTS.com


Strings – Recall Basics

Restricted Circulation | L&T Technology Services | www.LTTS.com


String Basics

char s1[10] = "abcdxyz";


char s2[] = "abcdxyz";
char s3[10] = { 'h', 'e', 'l', 'l', 'o', '\0'
Basics of Strings
};
char *ps = "abcdxyz";

String literal – Read Only


s1 a b c d x y z \
0 a b c d x y z \
s2 a b c d x y z \ 0
0
s3 h e l l o \
0
ps Heap
addr
Stack

Restricted Circulation | L&T Technology Services | www.LTTS.com


Simple I/O
char s1[15];  printf
char s2[15];  scanf
printf("Enter string 1\n");  getchar
scanf("%s",s1); //enter space separated  putchar
 gets (deprecated)
words
 puts
printf("Enter string 2\n");
scanf("%s",s2);
printf("%s,%s\n", s1, s2); //puts(s1),
puts(s2)

How to read multiple words separated by space?  Buffered I/O Issues


 Usage of fflush, __fpurge
 Space before format specifier in scanf
 Role of \n, beyond printing new line

Restricted Circulation | L&T Technology Services | www.LTTS.com


Basic Library Functions

strlen int strlen(const char*); Prototypes


char* strcpy(char*, const char*);
char* strcat(char*, const char*);
int strcmp(const char*, const char*);

strcpy

 Examples for each


 Nested usage of above functions
strcat  What if destination capacity is not enough for strcpy, strcat?
 Assumption – no overlapping between source & destination (Hint
– restrict pointers for better optimization when no overlapping,
no additional access to memory locations)
 Significance of const and non-const in above prototypes
strcmp
Reference

Restricted Circulation | L&T Technology Services | www.LTTS.com


Basic Library Functions

char s1[] = "Hello, How are char s1[20] = "Hello";


you?"; char s2[20] = "World";
int len = strlen(s1); char s3[20];
strcat(s1, s2);
strcat(s2, "abcd");
char s1[10] = "abcdxyz";
char s2[10];
char s3[10];
strcpy(s2, s1); char s1[20];
strcpy(s3, "hello"); char s2[20];
//Input the strings s1, s2
res = strcmp(s1, s2);
//if(strcmp(s1,s2)==0)
Visualize these code snippets using Python Tutor!

Restricted Circulation | L&T Technology Services | www.LTTS.com


Own Implementation

int mystrlen(const char*);


char* mystrcpy(char*, const char*); Implement your own string
functions, like std library
char* mystrcat(char*, const char*);
functions.
int mystrcmp(const char*, const char*);

Implement a function for string reverse.


int myputs(const char*);
int getString(char* buf, int maxlen);
//slightly changed version of gets

Restricted Circulation | L&T Technology Services | www.LTTS.com


Few more library Functions

strncpy strncat strncmp

strcasecmp strncasecmp strtok

strchr strrchr strstr

strspn strcspn strpbrk


Restricted Circulation | L&T Technology Services | www.LTTS.com
Passing String as an Argument of Function (str_arg)
#include<stdio.h>
void display(char []);

void display(char str[])


{
printf("String is %s",str);
}
int main()
{
char string[]="Hai";
display(string);
return 0;
}
Restricted Circulation | L&T Technology Services | www.LTTS.com
Returning String from a Function (ret_str)
#include<stdio.h>
void display(char []);

void display(char str[])

{
printf("String is %s",str);
}
int main()
{
char string[]="Hai";
display(string);
return 0;
}
Restricted Circulation | L&T Technology Services | www.LTTS.com
Raw Memory APIs & Conversions

Restricted Circulation | L&T Technology Services | www.LTTS.com


Raw Memory Operations

memcpy void* memcpy(void*, const void*, Prototypes


size_t);
int memcmp(const void*, const void*,
size_t);
memcmp void* memset(void*, int, size_t);
void* memchr(void*, int, size_t);
void* bzero(void*, size_t);

memset

bzero

memchr

Restricted Circulation | L&T Technology Services | www.LTTS.com


Raw Memory Operations - Examples

int xarr[10]={10, 20, 30, 40,


uint32_t val = 0x41424344;
50, 60, 70, 80, 90, 100
char arr[8];
};
memcpy(arr, &val, 4);
int yarr[10];
int zarr[10];
double dval = 5.6;
char buf[100];
memcpy(arr, &dval, 8);
memcpy(yarr, xarr, 20);
uint64_t lval;
memcpy(yarr, xarr + 5, 20);
memcpy(&lval, &dval, 8);
memcpy(buf, xarr, 40);

Restricted Circulation | L&T Technology Services | www.LTTS.com


Raw Memory Operations - Examples

char buf[100];
memset(buf, '*', 100); struct Sample {
//memset(buf, 0, 100); int x;
//memset(buf, '*', 40); float y;
//memset(buf+40, '$’, 60); double z;
char dummy[NBITS];
bzero(buf, 100); };
bzero(xarr, 5*sizeof(int));
struct sample s1;
bzero(&s1, sizeof(struct
Sample));
bzerof(&s1.dummy, NBITS);

Restricted Circulation | L&T Technology Services | www.LTTS.com


Raw Memory Operations - Examples

float fval=5.6f;
int arr[10]; double dval=5.6;
char buf[40]; int ival = 5;
memcmp(arr, buf, 40); int64_t lval = 5;
//memcmp(arr, buf, 20);
memcmp(&ival, &fval, 4)
uint32_t uval = 0x41424344; vs ival == fval
char carr[]="ABCD";
memcmp(&uval, carr, 4); memcpy(&lval, &dval, 8)
vs lval = dval

Restricted Circulation | L&T Technology Services | www.LTTS.com


Building & Parsing Strings

sprintf
int hh, mm, ss;
char tstr[10];
sscanf sprintf(tstr, "%02d:%02d:%02d",hh, mm,
ss);

snprintf for(i=0;i<n;i++) {
sprint(tbuf, “Employee:%d", (i+1);
puts(tbuf); //or any other
processing/comm
snscanf
}

char dstr[] = "15 12 2018";


sscanf(dstr, "%d%d%d", &dd, &mm, &yy);
From stdio.h

Restricted Circulation | L&T Technology Services | www.LTTS.com


Conversions to other types
strtoul

char nstr[]="2578";
strtol int val = strtoul(nstr, NULL, 10);

strtoll

char fstr[]="23.578 12.4578";


strtod char &pend;
float fval = strtof(fstr, &pend);
fval = strtof(pend, NULL);
strtof

strtoull Note:- atoi is deprecated API. Converting to other types

Restricted Circulation | L&T Technology Services | www.LTTS.com


Table of Strings

Restricted Circulation | L&T Technology Services | www.LTTS.com


Table of Strings – 2D Char Array

int n=5;
char tstr[n][20];
for(i=0;i<n;i++)
scanf("%d",tstr[i]);
for(i=0;i<n;i++)
printf("%d\n",tstr[i]);

int n=5;
char fstr[][10] =
{ "Hello","Welcome",
"black", "white",
"sunday", "April"};

Array of Strings Courtesy:- pythontutor.com for visualization

Restricted Circulation | L&T Technology Services | www.LTTS.com


Table of Strings – Array of Pointers

String Literals – Read only


int n=6;
char *vstr[] = {
"Hello","Welcome",
"black", "white",
"sunday", "April“
};
Stack

Courtesy:- pythontutor.com for


visualization

Passing Strings to Functions


Non-Contiguous memory
– variable length strings

Restricted Circulation | L&T Technology Services | www.LTTS.com


Command Line Arguments

int main(int argc, char* argv[]) { argc – No.of arguments


printf("No.of args : %d\n",argc);
printf("Prog name is : %s\ argv[0] - Program name, first argument
n",argv[0]);
for(int i=1;i<argc;i++) argv[1], argv[2], argv[3]
– subsequent arguments
printf("%d--%s\n",i,argv[i]);
}

How to run:-

./a.out 10 20 abc 2.3 xyz 30


(or) All command line arguments are
demo.exe 10 20 abc 2.3 xyz 30 received in the form of strings

Command Line Arguments

Restricted Circulation | L&T Technology Services | www.LTTS.com


Preprocessor Directives

Restricted Circulation | L&T Technology Services | www.LTTS.com


Preprocessor Directives
Lines starting with # are known as preprocessor-directives
In the 4 stage of code to executable conversion, the first stage is pre-
processing phase which expands the code based on ‘#’ symbol
These pre-processor provides an option to perform conditional decision
at this phase itself before the actual code compilation

Restricted Circulation | L&T Technology Services | www.LTTS.com


Features of Preprocessor Directives
Always preprocessor directives should start with #
Multiple directive cannot be added in a single line
No semicolon required at the end of directive
Although directives are usually placed in the beginning of the program,
it can be place anywhere in the program (inside or outside the
function)

Restricted Circulation | L&T Technology Services | www.LTTS.com


Main Functions of Preprocessor Directives
Macro Substitution
Macro with Arguments
Conditional Compilation
For File inclusion
Error Generation, compiler features with #pragma

Restricted Circulation | L&T Technology Services | www.LTTS.com


Lists of Preprocessor Directives
#include
#define
#undef
#ifdef
#ifndef
#if
#else
#elif
#endif
#error
#pragma

Restricted Circulation | L&T Technology Services | www.LTTS.com


Preprocessor #include
Basically this paste the code from mentioned file to the current file
All system defined libraries are included using this macro
There are variants as shown below:
#include<file>
#include “file”

Restricted Circulation | L&T Technology Services | www.LTTS.com


Macro #define
‘Macro’ is a symbol in the code which is replaced by value of macro, It
is defined by #define directive
Ex: #define PI 3.14
#define AND &&
There are two variants are macro as mentioned below:
Object Macros
Macros with Arguments

Restricted Circulation | L&T Technology Services | www.LTTS.com


Object Macro
This macro contains an identifier with definition, during pre-processing
the identifier is replaced by its defined value.
It is widely used to represent numeric constants.
For example: #define PI 3.1415
Here, PI is the macro name which will be replaced by the value 3.14.
#include<stdio.h>
#define PI 3.1415
int main()
{
printf(“%d”,PI);
return 0; -2039717128
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Nested Macro
#include<stdio.h>
#define ISLOWER(c) (c>=97 && c<=122)
#define ISUPPER(c) (c>=97 && c<=122)
#define ISALPHA(c) ISLOWER(c)||ISUPPER(c) //Nested Macro
int main()
{
char ch;
printf(“Enter a character”\n”);
scanf(“%c”,&ch);
if(ISALPHA(c))
printf(“\nEntered character is Alphabet”);
else
printf(“\nEntered character is not Alphabet”);
return 0;
}
Restricted Circulation | L&T Technology Services | www.LTTS.com
Issues with Macro
Problem with Macros is proper usage of parenthesis ( ) is required, if
not during expansion statement evaluation will be wrong.
#include<stdio.h>
#define PROD(x,y) x*y
int main()
{
printf(“%d”,PROD(2,4));
printf(“%d”,PROD(3+4,5+1));
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


Macro With Argument
This type of macros looks like a function call and online function
definition
Ex:
#define MAX(a,b) ((a)>(b)?(a):(b))
Here, MAX is the macro name
#include<stdio.h> #include<stdio.h>
#define MIN(x,y) ((x)<(y)?(x):(y)) #define SUM(x,y) ((x)+(y))
int main() int main()
{ {
printf(“Min number is %d”,MIN(2,4)); printf(“Sum is %d”,SUM(2,4));
return 0; return 0;
} }

Restricted Circulation | L&T Technology Services | www.LTTS.com


Function Vs Macros
Generally Macro expansion makes the code lengthy and increase the
compilation time
In functions passing of arguments and returning a value takes
sometime cause the execution time to be slow
In general function are slow but utilize less memory but macro
occupies more memory with less execution time

Restricted Circulation | L&T Technology Services | www.LTTS.com


#undef
To cancel an already defined macro, this #undefine directive is used.
Ex: #undef token
#include<stdio.h>
#define PROD(x,y) x*y
#undef PROD
int main()
{
printf(“%d”,PROD(2,4));
printf(“%d”,PROD(3+4,5+1));
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


#ifdef
This pre-processor directive is used for checking if a macro is defined
already in the source program.
It executes certain portion of the code if the respective macro is
defined
#ifdef MACRO
/* …Code to be executed….*/
#endif

Restricted Circulation | L&T Technology Services | www.LTTS.com


#if…#else
This preprocessor evaluates the expression and branches into two
based on conditions outcome.
It can be used with #if,#elif,#ifdef,#ifndef
Syntax:
#if expression
/* Code to be executed if the condition is satisfied*/
#else #include<stdio.h>
/*If the condition is not satisfied*/ #define NUMBER 1
#endif int main()
{
#if NUMBER ==0
printf(“Value of number is %d”,NUMBER);
#else
printf(“Value of number is non-zero”);
#endif
return 0;
}
Restricted Circulation | L&T Technology Services | www.LTTS.com
#if…#else
This preprocessor evaluates the expression and branches into two
based on conditions outcome.
It can be used with #if,#elif,#ifdef,#ifndef
Syntax:
#if expression
/* Code to be executed if the condition is satisfied*/
#else #include<stdio.h>
/*If the condition is not satisfied*/ #define NUMBER 1
#endif int main()
{
#ifdef NUMBER
printf(“Number is Defined”);
#else
printf(“Number is not Defined”);
#endif
return 0;
}
Restricted Circulation | L&T Technology Services | www.LTTS.com
#error
This preprocessor directive indicates error
• This is used for handling error, during compilation error this macro
helps in skipping the compilation process
#include<stdio.h>
#ifndef __MATH_H
#error Include Math Library
#else
int main()
{
float a;
a=sqrt(7)
printf(“%f”,a);
return 0;
}

Restricted Circulation | L&T Technology Services | www.LTTS.com


#pragma
This pre-processor directive gives additional information to the
compiler, which can be applied during pre-processor stage
This informs compiler to use/not to use certain OS features
Different Compilers may offer different usage of #pragma directive
Ex : Turning off structure padding, Executing function, Exiting a function

Restricted Circulation | L&T Technology Services | www.LTTS.com


Design Optimization

486 Restricted Circulation | L&T Technology Services | www.LTTS.com


Design Optimization

Design optimization is often a trade-off


between performance, resource usage,
power utilization, and compilation time.

487 Restricted Circulation | L&T Technology Services | www.LTTS.com


Design Optimization

Optimization Trade-Off
Trying to improve speed/performance Results in increased chip area and also
of the system by increasing resource increases the overall cost of the
usage and timing operations system developed
Example: To improve fast calculation,
trying to add extra ALU units and
Clock extension in processor
Trying to improve the power Results in area and timing trade-offs
requirements
Trying to minimize the system cost Affects the choice of device as it may
and time to market include a comparatively lesser number
of features or may have some other
drawbacks, like improper testing

488 Restricted Circulation | L&T Technology Services | www.LTTS.com


Considerations

Memory Time to
Usage Market

Processor
Selection

489 Restricted Circulation | L&T Technology Services | www.LTTS.com


Levels of Optimization

Lowest level of optimization. Simple optimizations are


-O0 performed to not impair debug view. This switch gives the
best possible debug view.

A restricted level giving a satisfactory debug view and


-O1 good code intensity.

A high level of optimization which might give a less


-O2 satisfactory debug view. This is the default option.

The highest, most aggressive level of optimization. The


optimizations performed depend on whether the -Ospace or -
-O3 Otime options are enabled. This typically leaves a poor debug
490 view. Restricted Circulation | L&T Technology Services | www.LTTS.com
GCC Optimization Levels

491 Restricted Circulation | L&T Technology Services | www.LTTS.com


GCC Optimization

Program Optimization

Code Power
Optimiza Time Consumptio
tion Optimizatio n
n

Optimizations can be enabled by using compiler flags.

492 Restricted Circulation | L&T Technology Services | www.LTTS.com


Compiler Flags

O0 O1 O2 O3

● The default option for code


compilation.
● It has the fastest compilation
time and is easy to debug
the code.

493 Restricted Circulation | L&T Technology Services | www.LTTS.com


Compiler Flags

O0 O1 O2 O3

● Moderate optimization to
reduce time and code
optimization.

494 Restricted Circulation | L&T Technology Services | www.LTTS.com


Compiler Flags

O0 O1 O2 O3

● Full optimization with slow


compilation time and it is
not easy to debug.

495 Restricted Circulation | L&T Technology Services | www.LTTS.com


Compiler Flags

O0 O1 O2 O3

● Full optimization with


slowest compilation time.
● May cause bugs in the
program and are not easy to
debug.

496 Restricted Circulation | L&T Technology Services | www.LTTS.com


Steps to Select Optimization

497 Restricted Circulation | L&T Technology Services | www.LTTS.com


Example - O0 Optimization

498 Restricted Circulation | L&T Technology Services | www.LTTS.com


Example - O1 Optimization

499 Restricted Circulation | L&T Technology Services | www.LTTS.com


Example - O2 Optimization

500 Restricted Circulation | L&T Technology Services | www.LTTS.com


Example - O3 Optimization

501 Restricted Circulation | L&T Technology Services | www.LTTS.com


Inline Functions

502 Restricted Circulation | L&T Technology Services | www.LTTS.com


Inline Functions

During
If the function function call By doing this,
definitions are instruction the compiler
small, then execution by eliminates the
the inline the compiler, function call
keyword can the compiler overhead and
be used at replaces the reduces the
function function call execution
declaration. with function time.
instructions.

503 Restricted Circulation | L&T Technology Services | www.LTTS.com


Inline Functions

504 Restricted Circulation | L&T Technology Services | www.LTTS.com


Inline Function

Short functions
defined inside the Inline function Bind all
class are can be statements
Evaluates
Parsed automatically terminated in the body
the
by the made as inline using curly of the
argument
compile functions. brackets. function.
only once.
r.

Defined Optimization of
Function ‘inline’ function Easy to debug
inside or An inline function
in C/C+ is based on because error
outside inside a class can
+ compiler and checking is done
the class. access the data
expands them during
members of the
all. compilation.
class.

505 Restricted Circulation | L&T Technology Services | www.LTTS.com


Macros
Never become
members of
class.

Encounters
binding problem
if it contains more
Defined at Always need Definition of macro than one
the to be/are ends with the new statement since it
beginning expanded. line. doesn’t have a
of the termination
program. symbol.

Evaluates the
Expanded
argument Difficult to debug
by the
every time it To be defined macros since error
preprocess
is used inside specifically. checking doesn’t
or.
the code. Can’t access data happen during
members of the class. compile time.

506 Restricted Circulation | L&T Technology Services | www.LTTS.com


Optimizing Variables

507 Restricted Circulation | L&T Technology Services | www.LTTS.com


Optimizing Variables

Local Variable Global Variable External Variables

● If you must use global ● If you must use external


variables, use static variables, group external
● Use local variables, variables with file scope data into structures or
preferably automatic rather than external arrays.
variables as much as variables whenever ● All elements of an
possible. possible. external structure use
● ● In a file with several
The compiler must make the same base address.
several worst-case related functions and ● Do not group variables
assumptions about global static variables, the whose addresses are
variables. optimizer can gather and taken with variables
use more information whose addresses are not
about how the variables taken.
are affected.

508 Restricted Circulation | L&T Technology Services | www.LTTS.com


Standards on Variables
All the
variables ‘NULL’
should be should be
initialized used for
before the pointers
actual usage. without an
initial
address.
Comma
operator (,) Example: char
should not be *a,b; //Is
used while variable b
declaring the also intended
variable. to be a
pointer.
509 Restricted Circulation | L&T Technology Services | www.LTTS.com
Avoid Type Conversion

To write an optimized code, use the same


type of variables for processing.

Avoid the usage of type conversion since that


takes extra machine cycles for data type
conversion.

510 Restricted Circulation | L&T Technology Services | www.LTTS.com


Compiler Optimization and Volatile Keyword

511 Restricted Circulation | L&T Technology Services | www.LTTS.com


Volatile

Useful to create Used by


variables whose memory-
values cannot mapped
be changed I/O control
inside the Provides reliable registers.
program access to
explicitly. special memory Volatile
Can be locations. data
changed by objects
an external can be
device/hard accessed/c
ware. hanged by
512
external
Restricted Circulation | L&T Technology Services | www.LTTS.com
What will be the Output?

For ‘a’ to be altered in a multi-


processing/ multi-threading
environment or hardware
attached variables, i.e., memory
mapped I/O, ‘a’ has to be
declared volatile.

513 Restricted Circulation | L&T Technology Services | www.LTTS.com


Unnecessary Optimization with ‘delay’ Loops

Based on the compiler


optimization setting,
Consider a ‘delay’ loop. the optimizer can
replace the loop into a
single assignment that
directly sets ‘t’ to the
final value.

514 Restricted Circulation | L&T Technology Services | www.LTTS.com


‘volatile’ turns off Optimization

By qualifying the variable ‘t’ with the ‘volatile’


keyword, this aggressive optimization can be
avoided.

515 Restricted Circulation | L&T Technology Services | www.LTTS.com


Data Alignment, Padding and Data Packing

516 Restricted Circulation | L&T Technology Services | www.LTTS.com


Data Alignment

Processor architecture Memory is byte


Reading all 4 bytes of integer in
align all data types in addressable and
one memory cycle is optimal.
C/C++. arranged sequentially.

A processor will have


processing word length If the memory is arranged as
as that of data bus single bank of one byte width,
size. On a 32-bit the processor needs to issue 4
machine, the memory read cycles to fetch
processing word size an integer.
will be 4 bytes.

517 Restricted Circulation | L&T Technology Services | www.LTTS.com


Data Alignment

518 Restricted Circulation | L&T Technology Services | www.LTTS.com


Word Size
32-bit Architecture

struct abc {
a b
char a;
char b; c
int c;
1st Clock 2nd Clock
} var; Cycle Cycle
char a Last 2 bytes
char b of int c
2 bytes of int
c
519 Restricted Circulation | L&T Technology Services | www.LTTS.com
Structure Padding
There will be To save
unnecessary the number
wastage of of cycles,
CPU cycles to the
store the compiler
variables. adds empty
bytes
Due to called
padding, padding.
The whole
empty variable will
memory get stored in
spaces are the memory
created. in one cycle.
520 Restricted Circulation | L&T Technology Services | www.LTTS.com
Structure Padding

EMPTY

a b

Total number of bytes = 1 byte + 1 byte + 2 bytes + 4


bytes = 8 bytes

521 Restricted Circulation | L&T Technology Services | www.LTTS.com


Structure Padding

The size is 8
bytes.

522 Restricted Circulation | L&T Technology Services | www.LTTS.com


Structure Padding

The size is 12
bytes.

523 Restricted Circulation | L&T Technology Services | www.LTTS.com


Structure Padding

● While interchanging the variable, the size of all the bytes is 12.

Empty Empty

a b
c
● Depending on the need for the speed of execution and memory
allocation, ‘Structure Padding’ can be disabled.

524 Restricted Circulation | L&T Technology Services | www.LTTS.com


Structure Padding

It is necessary to
avoid the structure
padding in C.
Structure padding is
performed by the
compiler. It
increases the size of
the structure
greater than the
size of the structure
members.

525 Restricted Circulation | L&T Technology Services | www.LTTS.com


Avoiding Structure Padding

Using #pragma pack(1) directive

Methods

Using attributes

526 Restricted Circulation | L&T Technology Services | www.LTTS.com


Using #pragma Pack(1)

527 Restricted Circulation | L&T Technology Services | www.LTTS.com


Using Attribute

528 Restricted Circulation | L&T Technology Services | www.LTTS.com


Pass by Reference

529 Restricted Circulation | L&T Technology Services | www.LTTS.com


Pass by Reference
Pass by value will
make a copy of
arguments while The return function is
passing a large the only option to
structure or class to send a value back to
a function. This leads the caller.
to performance
issues.
Pass by value It is often suitable to
increases processing use pass by
time and memory reference and modify
usage when more the argument to give
arguments are the value back to the
passed. caller function.
530 Restricted Circulation | L&T Technology Services | www.LTTS.com
Switch & Non-Contiguous Case Expressions

531 Restricted Circulation | L&T Technology Services | www.LTTS.com


Switch & Non-Contiguous Case Expressions

Switch is faster than the if-else ladder Cases must not have variable
due to ‘jump tables’. expression. Example: case 2+1

Since switch case makes use of


Fall through in ‘switch-case’
the jump table, it consumes
should be handled carefully.
more memory.

All switch cases should have a Standards violate the usage of


‘default’ block. Switch ‘Fall through’ design.

The memory allocated using


Float expressions cannot be dynamic memory allocation
tested using switch-case. functions should be allocated
explicitly.

532 Restricted Circulation | L&T Technology Services | www.LTTS.com


Loop Overheads

Nested if-
Dead code
else-if

533 Restricted Circulation | L&T Technology Services | www.LTTS.com


Loop Unrolling

To reduce the loop overhead, reduce the number of


iterations of the loop.

Before loop After loop


unrolling unrolling

534 Restricted Circulation | L&T Technology Services | www.LTTS.com


Portability

535 Restricted Circulation | L&T Technology Services | www.LTTS.com


Portability

C Code is more
C code is A program can be
portable and can
efficient, easy to written on one
be compiled in
understand, machine and run
other platforms
maintain and on other
with least
debug. machines.
modifications.

536 Restricted Circulation | L&T Technology Services | www.LTTS.com


Loop Hoisting

537 Restricted Circulation | L&T Technology Services | www.LTTS.com


Loop Hoisting
To improve run-time performance, hoist Loop-invariant
expressions out of loops. The loop invariant expression is to
be run only once rather than at each iteration.

Code snippet before the loop invariant Code snippet after the loop invariant
expression has been hoisted out of the loop expression has been hoisted out of the loop

538 Restricted Circulation | L&T Technology Services | www.LTTS.com


Thank You !

You might also like