0% found this document useful (0 votes)
2 views84 pages

DDCA AppC

The document is an appendix on C programming from the book 'Digital Design & Computer Architecture' by Sarah Harris and David Harris. It covers various topics including control-flow statements, data types, functions, and operators, providing a comprehensive overview of C programming and its applications in computer architecture. The appendix serves as a bridge between hardware concepts and software programming, allowing readers to understand the connection between the two.

Uploaded by

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

DDCA AppC

The document is an appendix on C programming from the book 'Digital Design & Computer Architecture' by Sarah Harris and David Harris. It covers various topics including control-flow statements, data types, functions, and operators, providing a comprehensive overview of C programming and its applications in computer architecture. The appendix serves as a bridge between hardware concepts and software programming, allowing readers to understand the connection between the two.

Uploaded by

mazharnaseemsurf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Digital Design &

Computer Architecture
Sarah Harris & David Harris

Appendix C:
C Programming
C. 7 Control-Flow Statements
The overall goal of this book is to give a picture of how computers work on

Appendix C :: Topics
C. 8 More Data Types
many levels, from the transistors by which they are constructed all the way up
C. 9 Standard Libraries
to the software they run. The first five chapters of this book work up through
C. 10 Compiler and Command Line
the lower levels of abstraction, from transistors to gates to logic design.
Options
Chapters 6 through 8 jump up to architecture and work back down to micro-
C. 11 Common Mistakes
architecture to connect the hardware with the software. This Appendix on C
programming fits logically between Chapters 5 and 6, covering C program-
• C Basics
ming as the highest level of abstraction in the text. It motivates the architec-
ture material and links this book to programming experience that may
Application
Software
>”hello
world!”

• Functions
already be familiar to the reader. This material is placed in the Appendix
so that readers may easily cover or skip it depending on previous experience.
Operating
Systems
Programmers use many different languages to tell a computer what to
• Operators
do. Fundamentally, computers process instructions in machine language
consisting of 1’s and 0 ’s, as is explored in Chapter 6. But programming
Architecture

• Control Flow
in machine language is tedious and slow, leading programmers to use more
abstract languages to get their meaning across more efficiently. Table eC.1
Micro-
architecture

• Loops
lists some examples of languages at various levels of abstraction.
One of the most popular programming languages ever developed is Logic +
called C. It was created by a group including Dennis Ritchie and Brian
• Arrays & Strings
Kernighan at Bell Laboratories between 1969 and 1973 to rewrite the
UNIX operating system from its original assembly language. By many
Digital
Circuits

• Structures
measures, C (including a family of closely related languages such as C++,
C#, and Objective C) is the most widely used language in existence. Its Analog
Circuits
+

popularity stems from a number of factors including its:
• Memory
▶ Availability on a tremendous variety of platforms, from supercomputers Devices
down to embedded microcontrollers
• Pointers
▶ Relative ease of use, with a huge user base Physics

• Dynamic Memory Allocation


541.e1

2 Digital Design & Computer Architecture Digital Building Blocks


Overview
• C programming language developed at Bell Labs
around 1973
• Capable of controlling a computer to do nearly
anything, including directly interacting with the
hardware
• Suitable for generating high performance code
• Relatively easy to use
• Available from supercomputers to microcontrollers
• Closely related to other important languages
including C++, C#, Objective C, Java, Arduino

3 Digital Design & Computer Architecture Digital Building Blocks


C is Libertarian
• Lets you do just about anything
• Interacts directly with the hardware
• Does NOT protect you from your own
stupidity
• Assumes YOU know the size of arrays and
variables
• Unless sandboxed, can write ANYWHERE in
memory

4 Digital Design & Computer Architecture Digital Building Blocks


Example
// factorial.c
// [email protected] 22 October 2019

int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}

void main(void) {
int result;
result = fact(4);
}

5 Digital Design & Computer Architecture Digital Building Blocks


Steps to C Programming
• Write code
• Compile code
• Execute code
• Debug code

6 Digital Design & Computer Architecture Digital Building Blocks


Appendix C: C Programming

C Basics
Comments
• Single-line comments begin with “//” and continue to the
end of the line.
x += 2; //This is a single-line comment.

• Multi-line comments begin with “/*” end with “*/”.


/* You can hide or disable a section of code
such as this block with a multi-line comment
x = bob ? x : y;
y -= 5;
*/
• Always start code with the file name, your name, email, and
date. This gives you copyright ownership & helps the next
programmer track you down.

8 Digital Design & Computer Architecture Digital Building Blocks


Constants, Defines, or Macros
• Constants are named using the #define directive
#define MAXGUESSES 5
#define PI 3.14159
• The # indicates that this line in the program will be
handled by the preprocessor.
• Before compilation, the preprocessor replaces each
occurrence of the identifier MAXGUESSES in the
program with 5.
• By convention, #define lines are located at the top
of the file and identifiers are written in all capital
letters.

9 Digital Design & Computer Architecture Digital Building Blocks


Global and Local Variables
• Global variables are declared outside of any
function
– Accessible from all functions
– Often lead to hard-to-debug code
– Should be avoided, especially in large programs
• Local variables are declared inside a function
– Only accessible in that function
– Should be your preferred choice

10 Digital Design & Computer Architecture Digital Building Blocks


ter can be viewed as either an ASCII value or an 8-bit integer.1 Table eC.2

Primitive Data Types


lists the size and range of each primitive type. Integers may be 16, 32,
or 64 bits. They use two’s complement unless qualified as unsigned.
Table eC.2 Primitive data types and sizes

Type Size (bits) Minimum Maximum


char 8 −2−7 = −128 27 − 1 = 127

unsigned char 8 0 28 − 1 = 255

short 16 −215 = −32,768 215 − 1 = 32,767

unsigned short 16 0 216 − 1 = 65,535

long 32 −231 = −2,147,483,648 231 − 1 = 2,147,483,647

unsigned long 32 0 232 − 1 = 4,294,967,295

long long 64 −263 263 − 1

unsigned long 64 0 264 − 1

int machine-dependent

unsigned int machine-dependent

float 32 ±2−126 ±2127

double 64 ±2−1023 ±21022

1
Technically, the C99 standard defines a character as “a bit representation that fits in a
byte,” without requiring a byte to be 8 bits. However, current systems define a byte as 8 bits.
11 Digital Design & Computer Architecture Digital Building Blocks
Integer Sizes
• Integer sizes in C may vary with the machine
– int may be 16 or 32 bits
– long may be 32 or 64 bits
– Best to use sized types if size truly matters
– But their names are a bit cumbersome
• Signed: int16_t, int32_t, int64_t
• Unsigned: uint16_t, uint32_t, uint64_t

12 Digital Design & Computer Architecture Digital Building Blocks


ASCII Table

https://commons.wikimedia.org/wiki/File:ASCII-Table.svg

13 Digital Design & Computer Architecture Digital Building Blocks


Appendix C: C Programming

Functions
Functions
• A function may take some inputs and may return at most
one output
• The type of the inputs is declared in the function
declaration
• Functions pass variables by value not reference
• Curly braces {} enclose the body of the function, which may
contain zero or more statements
• The type of returned value is declared in the function
declaration
• The return statement indicates the value that the function
should return to its caller
• A function must be either declared BEFORE it is used or a
function prototype declared BEFORE it is used

15 Digital Design & Computer Architecture Digital Building Blocks


Function Example
// Return the sum of the three input variables

int sum3(int a, int b, int c) {


int result = a + b + c;
return result;
}

16 Digital Design & Computer Architecture Digital Building Blocks


Function Prototypes
// sum3example.c
// [email protected] 22 October 2019

////////////////////////////////
// Prototypes
////////////////////////////////
int sum3(int, int, int); // needed because sum3 is called before declared

////////////////////////////////
// main
////////////////////////////////

void main(void) {
int answer;
answer = sum3(6, 7, 8);
}

////////////////////////////////
// other functions
// prototype not needed if thsse were moved before main
////////////////////////////////

int sum3(int a, int b, int c) {


int result = a + b + c;
return result;
}

17 Digital Design & Computer Architecture Digital Building Blocks


Prototypes are Sometimes Unavoidable
// Prototypes needed for f1 and/or f2 because they
// can’t both be declared before each other

int f1(int);
int f2(int);

int f1(int n) {
return f2(n-1) + 1;
}

int f2(int n) {
return f1(n-1)*2;
}

void main(void) {
int answer;
answer = f1(5);
}

18 Digital Design & Computer Architecture Digital Building Blocks


Includes
• The function prototypes for the standard libraries
are included at the top of a file with the
#include directive:
#include <stdio.h>
#include <math.h>

• Your own function prototypes (or anything else


you want to include) is done with quotes instead
of brackets for relative or absolute path:
e.g., #include "other/myFuncs.h"

19 Digital Design & Computer Architecture Digital Building Blocks


Appendix C: C Programming

Operators
Boolean (True/False) in C
• A variable or expression is considered FALSE if its
value is 0
• A variable is considered TRUE if it has any other value
– 1, 42, and -1 are all TRUE for C
• Logical operators assign FALSE as 0 and TRUE as 1

21 Digital Design & Computer Architecture Digital Building Blocks


541.e12 APPENDIX C

Operators and Precedence


Table eC.3 Operators listed by decreasing precedence

Category Operator Description Example


Unary ++ post-increment a++; // a = a+1

−− post-decrement x--; // x = x−1

& memory address of a variable x = &y; // x = the memory


// address of y

~ bitwise NOT z = ~a;

! Boolean NOT !x

− negation y = -a;

++ pre-increment ++a; // a = a+1

−− pre-decrement --x; // x = x−1

(type) casts a variable to (type) x = (int)c; // cast c to an


// int and assign it to x

sizeof() size of a variable or type in bytes long int y;


x = sizeof(y); // x = 4

Multiplicative * multiplication y = x * 12;

/ division z = 9 / 3; // z = 3
22 Digital Design & Computer Architecture Digital Building Blocks
% modulo z = 5 % 2; // z = 1
(type) casts a variable to (type) x = (int)c; // cast c to an

Operators Continued
sizeof() size of a variable or type in bytes
// int and assign it to x

long int y;
x = sizeof(y); // x = 4

Multiplicative * multiplication y = x * 12;

/ division z = 9 / 3; // z = 3

% modulo z = 5 % 2; // z = 1

Additive + addition y = a + 2;

− subtraction y = a - 2;

Bitwise Shift << bitshift left z = 5 << 2; // z = 0b00010100

>> bitshift right x = 9 >> 3; // x = 0b00000001

Relational == equals y == 2

!= not equals x != 7

< less than y < 12

> greater than val > max

<= less than or equal z <= 2

>= greater than or equal y >= 10

23 Digital Design & Computer Architecture Digital Building Blocks


Operators Continued C.5 Operators 541.e13

Table eC.3 Operators listed by decreasing precedence—Cont’d

Category Operator Description Example


Bitwise & bitwise AND y = a & 15;

^ bitwise XOR y = 2 ^ 3;

| bitwise OR y = a | b;

Logical && Boolean AND x && y

|| Boolean OR x || y

Ternary ?: ternary operator y = x ? a : b; // if x is TRUE,


// y=a, else y=b

Assignment = assignment x = 22;

+= addition and assignment y + = 3; // y = y + 3

−= subtraction and assignment z −= 10; // z = z – 10

*= multiplication and assignment x *= 4; // x = x * 4

/= division and assignment y /= 10; // y = y / 10

%= modulo and assignment x %= 4; // x = x % 4


24 Digital Design & Computer Architecture Digital Building Blocks
>>= bitwise right-shift and assignment x >>= 5; // x = x>>5
Logical && Boolean AND x && y

Operators Continued
Ternary
||

?:
Boolean OR

ternary operator
x || y

y = x ? a : b; // if x is TRUE,
// y=a, else y=b

Assignment = assignment x = 22;

+= addition and assignment y + = 3; // y = y + 3

−= subtraction and assignment z −= 10; // z = z – 10

*= multiplication and assignment x *= 4; // x = x * 4

/= division and assignment y /= 10; // y = y / 10

%= modulo and assignment x %= 4; // x = x % 4

>>= bitwise right-shift and assignment x >>= 5; // x = x>>5

<<= bitwise left-shift and assignment x <<= 2; // x = x<<2

&= bitwise AND and assignment y &= 15; // y = y & 15

|= bitwise OR and assignment x |= y; // x = x | y

^= bitwise XOR and assignment x ^= y; // x = x ^ y

operators. Within the same category, operators are evaluated in the order
that they appear in the program.
Unary operators, also called monadic operators, have a single operand.
Ternary operators have three operands, and all others have two. The
25 Digital
ternary Design
operator & Computer
(from Architecture
the Latin ternarius meaningDigital Building
consisting Blocks
of three)
Examples
int a = 42;
int b = 0x15; // hexadecimal; = 21 in decimal
char c = 0b00001010; // binary; = 10 in decimal

char d = !c; // 0, because c was nonzero


char e = ~c; // 0b11110101 bitwise NOT
char f = e | c; // 0b11111111 bitwise OR
char g = c << 2; // 0b00101000 shift left by 2
int h = (a > b); // 1 because a is greater than b
int i = (a > b)&&(c != e); // 1 because both are TRUE
int j = (a > b) ? a : b; // 42 because a > b
int k = sizeof(a); // 4 on most computers
g &= c; // 0b00001000 bitwise AND

26 Digital Design & Computer Architecture Digital Building Blocks


Appendix C: C Programming

Control Flow
Control Flow Statements
if
if (expression)
statement;

if/else
if (expression)
statement1;
else
statement2;

switch/case
switch (variable) {
case (expression1): statement1; break;
case (expression2): statement2; break;
case (expression3): statement3; break;
default: statement4;
}

Don’t forget “break” or “default”

28 Digital Design & Computer Architecture Digital Building Blocks


If example
if (n <= 1) return 1;

29 Digital Design & Computer Architecture Digital Building Blocks


Compound Statements
• When a statement has more than one line, enclose it in {}
if (answer == 42) {
ultimateQuestion = 1;
hitchhikersGuide = 1;
}

30 Digital Design & Computer Architecture Digital Building Blocks


If/else example
if (n <= 1) return 1;
else return fact(n-1);

31 Digital Design & Computer Architecture Digital Building Blocks


Switch/case example
switch (state) {
case (0): if (ta) state = 0; else state = 1; break;
case (1): state = 2; break;
case (2): if (tb) state = 2; else state = 3; break;
case (3): state = 0; break;
default: state = 0;
}

32 Digital Design & Computer Architecture Digital Building Blocks


Appendix C: C Programming

Loops
Loops
while
while (condition)
statement;

do/while
do {
statement;
} while (condition);

for
for (initialization; condition; loop operation)
statement;

34 Digital Design & Computer Architecture Digital Building Blocks


While example
int fact(int n) {
int result = 1;
while (n > 1) {
result = result * n; // or write result *= n;
n = n – 1; // or write n--
}
return result;
}

// Alternative while loop is shorter but less clear

int fact(int n) {
int result = 1;
while (n > 1) result *= n--;
return result;
}

35 Digital Design & Computer Architecture Digital Building Blocks


Do/while example
int fact(int n) {
int result = 1;
do {
result *= n;
} while (n-- > 1);
return result;
}

• Do always executes the statement at least once.


• Longer and not preferred for this example

36 Digital Design & Computer Architecture Digital Building Blocks


For example
int fact(int n) {
int result = 1;
int i;

for (i=1; i <= n; i++)


result *= i;
return result;
}

• First do initialization (i = 1)
• Then check condition (i<=n)
• If satisfied, do body (result *= i)
• Then do loop operation (i++)
• Then repeat from checking condition

37 Digital Design & Computer Architecture Digital Building Blocks


Appendix C: C Programming

Arrays & Strings


Data Types: Arrays
• Array contains multiple elements
float accel[3];
• The elements are numbered from 0 to N−1, where
N is the length of the array
• Initialize your arrays.
– An uninitialized array can contain anything
• Arrays can be multidimensional
#define NUMSTUDENTS 120
#define NUMLABS 11
int grades[NUMSTUDENTS][NUMLABS];

39 Digital Design & Computer Architecture Digital Building Blocks


Array Example
#include <math.h>

double mag(double v[3]) {


return sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
}

40 Digital Design & Computer Architecture Digital Building Blocks


Data Types: Strings
• A string is an array of characters
• Last entry is zero to indicate end (”NULL terminated”)
char name[20] = "BOB";
• Stored as:
name[0] = 66; // ASCII value for B
name[1] = 79; // ASCII value for O
name[2] = 66; // ASCII value for B
name[3] = 0; // NULL termination
other entries are junk, ignored

41 Digital Design & Computer Architecture Digital Building Blocks


Examples: String Handling
#define MAXLEN 80

int strlen(char str[]) {


int len=0;

while (str[len] && len < MAXLEN) len++;


return len;
}

void strcpy(char dest[], char src[]) {


int i = 0;

do {
dest[i] = src[i];
} while (src[i++] && i < MAXLEN);
}

42 Digital Design & Computer Architecture Digital Building Blocks


Examples: Using Strings
#include <string.h>
#define MAXLEN 80

void main(void) {
char name[80];
int len;
char c;

strcpy(name, "BOB"); // copy BOB into name


len = strlen(name); // len = 3
c = name[1]; // c = 'O' (79)
}

43 Digital Design & Computer Architecture Digital Building Blocks


Appendix C: C Programming

Structures
Structures
• Store a collection of related information
• General format:
struct name {
type1 element1;
type2 element2;
...
};

45 Digital Design & Computer Architecture Digital Building Blocks


Structures
struct contact {
char name[30];
int age;
float height; // in meters
};

struct contact c1;


strcpy(c1.name, "Ben Bitdiddle”);
c1.age = 20;
c1.height = 1.82;

46 Digital Design & Computer Architecture Digital Building Blocks


Typedef
• If you’re using lots of the same structure, you can
shorten your typing by using typedef.
• typedef type name;

typedef struct contact {


char name[30];
int age;
float height; // in meters
} contact; // defines contact as shorthand for "struct contact”

contact c1; // now we can declare the variable as type contact

47 Digital Design & Computer Architecture Digital Building Blocks


Structure Examples
typedef struct point { typedef struct rect {
int x; point ll;
int y; point ur;
} point; int color;
} rect;
point p1;
p1.x = 42; p1.y = 9; rect r1;
r1.color = 1;
r1.ll = p1;
r1.ur.x = r1.ll.x + width;
r1.ur.y = r1.ll.y + height;

48 Digital Design & Computer Architecture Digital Building Blocks


Appendix C: C Programming

Memory
Memory
• Variables are stored in memory
• Each primitive data type has a size
– char 1 byte
– short at least 2 bytes
– long at least 4 bytes, 8 on some 64-bit computers
– int at least 2 bytes, 4 on most 32 & 64-bit computers
– float 4 bytes
– double 8 bytes
• Arrays & structs stored in multiple consecutive locations

50 Digital Design & Computer Architecture Digital Building Blocks


Sizeof
• Sizeof operator returns size of a datatype

char c;
double d;
point p;
rect r;
int s1 = sizeof c; // s1 = 1
int s2 = sizeof(d); // s2 = 8
int s3 = sizeof(p); // s3 = 4 + 4 = 8
int s4 = sizeof(r); // s4 = 8 + 8 + 4 = 20

51 Digital Design & Computer Architecture Digital Building Blocks


body of the code, as shown in C Code Example eC.22. Each element of an

Memory Example: Array


array is accessed using brackets []. The contents of memory containing the
array are shown in Figure eC.4. Array initialization using curly braces {} can
only be performed at declaration, and not afterward. for loops are commonly
used to assign and read array data, as shown in C Code Example eC.23 .

C Code Example eC.21 ARRAY INITIALIZATION AT DECLARATION USING { }

long scores[3]={93, 81, 97}; // scores[0]=93; scores[1]=81; scores[2]=97;

Address Data Variable Name Address Data Variable Name


(Byte
.. #) (Byte
.. #)
. .
0x4B 0x4B 0x00
0x4A 0x4A 0x00
0x49 97 0x49 0x00
0x48 scores[2] 0x48 0x61 scores[2]
0x47 0x47 0x00
0x46 0x46 0x00 Figure eC.4 scores array
0x45 81 0x45 0x00 stored in memory
0x44 scores[1] 0x44 0x51 scores[1]
0x43 0x43 0x00
0x42 0x42 0x00
0x41 93 0x41 0x00
0x40 scores[0] 0x40 0x5D scores[0]

Memory Memory

52 Digital Design & Computer Architecture Digital Building Blocks


Memory Example: Structure

53 Digital Design & Computer Architecture Digital Building Blocks


Appendix C: C Programming

Pointers
Pointers
• A pointer is an address in memory
• Pointer variables are declared with * and a data type
to which the pointer points
int salary1, salary2;
int *ptr; // a pointer to an integer
• & returns address of a variable
salary1 = 98500; // suppose this is at address 100 in memory
ptr = &salary1; // ptr contains 100 (the address of salary1)

• * dereferences a pointer (finds value it points to)


salary2 = *ptr + 1000; // salary2 gets 99500

55 Digital Design & Computer Architecture Digital Building Blocks


Arrays and Pointers
• An array in C is viewed as the address of the zeroth
element
• Equivalent to a pointer to the beginning of the array

56 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b;
0x1038 x
int *ptr;
int i; 0x1034 x
0x1030 x
0x102C x
0x1028 x
0x1024 x
0x1020 x
0x101C x
0x1018 1 r1.color
0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

57 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b;
0x1038 x
int *ptr;
int i; 0x1034 x
0x1030 x
0x102C x
0x1028 x ary[3]
0x1024 x ary[2]
0x1020 x ary[1]
0x101C x ary[0]
0x1018 1 r1.color
0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

58 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b; // suppose at addresses 0x102C, 0x1030
0x1038 x
int *ptr;
int i; 0x1034 x
0x1030 x b
0x102C 37 a
0x1028 x ary[3]
0x1024 x ary[2]
0x1020 x ary[1]
0x101C x ary[0]
0x1018 1 r1.color
0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

59 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b; // suppose at addresses 0x102C, 0x1030
0x1038 x
int *ptr; // suppose ptr is at address 0x1034, initially undefined
int i; 0x1034 x ptr
0x1030 x b
0x102C 37 a
0x1028 x ary[3]
0x1024 x ary[2]
0x1020 x ary[1]
0x101C x ary[0]
0x1018 1 r1.color
0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

60 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b; // suppose at addresses 0x102C, 0x1030
0x1038 x i
int *ptr; // suppose ptr is at address 0x1034, initially undefined
int i; 0x1034 x ptr
0x1030 x b
0x102C 37 a
0x1028 x ary[3]
0x1024 x ary[2]
0x1020 x ary[1]
0x101C x ary[0]
0x1018 1 r1.color
0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

61 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b; // suppose at addresses 0x102C, 0x1030
0x1038 x i
int *ptr; // suppose ptr is at address 0x1034, initially undefined
int i; 0x1034 x ptr
0x1030 x b
for (i=0; i<3; i++) ary[i] = i*i; 0x102C 37 a
ptr = &a;
0x1028 x ary[3]
b = *ptr;
*ptr = 3; 0x1024 x ary[2]
ptr = ary; 0x1020 x ary[1]
ptr[1] = b; 0x101C x ary[0]
*(ptr+2) = 7;
0x1018 1 r1.color
ary[4] = 1;
*(ptr+5) = 2; 0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

62 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b; // suppose at addresses 0x102C, 0x1030
0x1038 3 i
int *ptr; // suppose ptr is at address 0x1034, initially undefined
int i; 0x1034 x ptr
0x1030 x b
for (i=0; i<3; i++) ary[i] = i*i; // Note: ary[3] not changed 0x102C 37 a
ptr = &a;
0x1028 x ary[3]
b = *ptr;
*ptr = 3; 0x1024 4 ary[2]
ptr = ary; 0x1020 1 ary[1]
ptr[1] = b; 0x101C 0 ary[0]
*(ptr+2) = 7;
0x1018 1 r1.color
ary[4] = 1;
*(ptr+5) = 2; 0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

63 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b; // suppose at addresses 0x102C, 0x1030
0x1038 3 i
int *ptr; // suppose ptr is at address 0x1034, initially undefined
int i; 0x1034 0x102C ptr
0x1030 x b
for (i=0; i<3; i++) ary[i] = i*i; 0x102C 37 a
ptr = &a; // ptr = 0x102C
0x1028 x ary[3]
b = *ptr;
*ptr = 3; 0x1024 4 ary[2]
ptr = ary; 0x1020 1 ary[1]
ptr[1] = b; 0x101C 0 ary[0]
*(ptr+2) = 7;
0x1018 1 r1.color
ary[4] = 1;
*(ptr+5) = 2; 0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

64 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b; // suppose at addresses 0x102C, 0x1030
0x1038 3 i
int *ptr; // suppose ptr is at address 0x1034, initially undefined
int i; 0x1034 0x102C ptr
0x1030 37 b
for (i=0; i<3; i++) ary[i] = i*i; 0x102C 37 a
ptr = &a; // ptr = 0x102C
0x1028 x ary[3]
b = *ptr; // dereference pointer, b = 37
*ptr = 3; 0x1024 4 ary[2]
ptr = ary; 0x1020 1 ary[1]
ptr[1] = b; 0x101C 0 ary[0]
*(ptr+2) = 7;
0x1018 1 r1.color
ary[4] = 1;
*(ptr+5) = 2; 0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

65 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b; // suppose at addresses 0x102C, 0x1030
0x1038 3 i
int *ptr; // suppose ptr is at address 0x1034, initially undefined
int i; 0x1034 0x102C ptr
0x1030 37 b
for (i=0; i<3; i++) ary[i] = i*i; 0x102C 3 a
ptr = &a; // ptr = 0x102C
0x1028 x ary[3]
b = *ptr; // dereference pointer, b = 37
*ptr = 3; // a = 3 0x1024 4 ary[2]
ptr = ary; 0x1020 1 ary[1]
ptr[1] = b; 0x101C 0 ary[0]
*(ptr+2) = 7;
0x1018 1 r1.color
ary[4] = 1;
*(ptr+5) = 2; 0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

66 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b; // suppose at addresses 0x102C, 0x1030
0x1038 3 i
int *ptr; // suppose ptr is at address 0x1034, initially undefined
int i; 0x1034 0x101C ptr
0x1030 37 b
for (i=0; i<3; i++) ary[i] = i*i; 0x102C 3 a
ptr = &a; // ptr = 0x102C
0x1028 x ary[3]
b = *ptr; // dereference pointer, b = 37
*ptr = 3; // a = 3 0x1024 4 ary[2]
ptr = ary; // ptr = 0x101C 0x1020 1 ary[1]
ptr[1] = b; 0x101C 0 ary[0]
*(ptr+2) = 7;
0x1018 1 r1.color
ary[4] = 1;
*(ptr+5) = 2; 0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

67 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b; // suppose at addresses 0x102C, 0x1030
0x1038 3 i
int *ptr; // suppose ptr is at address 0x1034, initially undefined
int i; 0x1034 0x101C ptr
0x1030 37 b
for (i=0; i<3; i++) ary[i] = i*i; 0x102C 3 a
ptr = &a; // ptr = 0x102C
0x1028 x ary[3]
b = *ptr; // dereference pointer, b = 37
*ptr = 3; // a = 3 0x1024 4 ary[2]
ptr = ary; // ptr = 0x101C 0x1020 37 ary[1]
ptr[1] = b; // ary[1] = 37 0x101C 0 ary[0]
*(ptr+2) = 7;
0x1018 1 r1.color
ary[4] = 1;
*(ptr+5) = 2; 0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

68 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b; // suppose at addresses 0x102C, 0x1030
0x1038 3 i
int *ptr; // suppose ptr is at address 0x1034, initially undefined
int i; 0x1034 0x101C ptr
0x1030 37 b
for (i=0; i<3; i++) ary[i] = i*i; 0x102C 3 a
ptr = &a; // ptr = 0x102C
0x1028 x ary[3]
b = *ptr; // dereference pointer, b = 37
*ptr = 3; // a = 3 0x1024 7 ary[2]
ptr = ary; // ptr = 0x101C 0x1020 37 ary[1]
ptr[1] = b; // ary[1] = 37 0x101C 0 ary[0]
*(ptr+2) = 7; // ary[2] = 7, note offset is in int sizes, not bytes
0x1018 1 r1.color
ary[4] = 1;
*(ptr+5) = 2; 0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

69 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b; // suppose at addresses 0x102C, 0x1030
0x1038 3 i
int *ptr; // suppose ptr is at address 0x1034, initially undefined
int i; 0x1034 0x101C ptr
0x1030 37 b
for (i=0; i<3; i++) ary[i] = i*i; 0x102C 1 a
ptr = &a; // ptr = 0x102C
0x1028 x ary[3]
b = *ptr; // dereference pointer, b = 37
*ptr = 3; // a = 3 0x1024 7 ary[2]
ptr = ary; // ptr = 0x101C 0x1020 37 ary[1]
ptr[1] = b; // ary[1] = 37 0x101C 0 ary[0]
*(ptr+2) = 7; // ary[2] = 7, note offset is in int sizes, not bytes
0x1018 1 r1.color
ary[4] = 1; // a = 1, BAD: trash variable past end of array
*(ptr+5) = 2; 0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

70 Digital Design & Computer Architecture Digital Building Blocks


Pointer Example
Now add: Address Data Var. Name
int ary[4]; // suppose at addresses 0x101C, 0x1020, 0x1024, 0x1028 0x103C x
int a = 37, b; // suppose at addresses 0x102C, 0x1030
0x1038 3 i
int *ptr; // suppose ptr is at address 0x1034, initially undefined
int i; 0x1034 0x101C ptr
0x1030 2 b
for (i=0; i<3; i++) ary[i] = i*i; 0x102C 1 a
ptr = &a; // ptr = 0x102C
0x1028 x ary[3]
b = *ptr; // dereference pointer, b = 37
*ptr = 3; // a = 3 0x1024 7 ary[2]
ptr = ary; // ptr = 0x101C 0x1020 37 ary[1]
ptr[1] = b; // ary[1] = 37 0x101C 0 ary[0]
*(ptr+2) = 7; // ary[2] = 7, note offset is in int sizes, not bytes
0x1018 1 r1.color
ary[4] = 1; // a = 1, BAD: trash variable past end of array
*(ptr+5) = 2; // b = 2, BAD: trash variable past end of array 0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

71 Digital Design & Computer Architecture Digital Building Blocks


Another Example
C Code Program Output

#include <stdio.h>

int main (void)


{ age = 30
char age = 30; p = 0x7ffee311e82b
char *p; *p = 30
p = &age; sizeof(age) = 1
printf("age = %d\n", age); sizeof(p) = 8
printf("p = %p\n", p); *p = 40
printf("*p = %d\n", *p); age = 40
printf("sizeof(age) = %ld\n", sizeof(age));
printf("sizeof(p) = %ld\n", sizeof(p));
*p = 40;
printf("*p = %d\n", *p);
printf("age = %d\n", age);
return 0;
}

72 Digital Design & Computer Architecture Digital Building Blocks


Another Example
C Code Program Output

#include <stdio.h>

int main (void)


{ age = 30
char age = 30; p = 0x7ffee311e82b
char *p; *p = 30
p = &age; sizeof(age) = 1
printf("age = %d\n", age); sizeof(p) = 8
printf("p = %p\n", p); *p = 40
printf("*p = %d\n", *p); age = 40
printf("sizeof(age) = %ld\n", sizeof(age));
printf("sizeof(p) = %ld\n", sizeof(p));
*p = 40;
printf("*p = %d\n", *p);
printf("age = %d\n", age);
return 0;
}

73 Digital Design & Computer Architecture Digital Building Blocks


Pointers and Structures
Address Data Var. Name
rect *rptr; // Let rptr know it’s pointing to a rect 0x103C x
rptr = &r1; // Have rptr point at r1 0x1038 3 i
0x1034 0x101C ptr
0x1030 2 b
(*rptr).color = 3; // Change r1.color to 3
0x102C 1 a
rptr->color = 4; // Change r1.color to 4 0x1028 x ary[3]
0x1024 7 ary[2]
// Use dot “.” when you are using the structure name. 0x1020 37 ary[1]
// Arrow “->” (member access operator) is preferred 0x101C 0 ary[0]
when you are using the pointer. 0x1018 1 r1.color
0x1014 9 + height r1.ur.y
0x1010 42 + width r1.ur.x
0x100C 9 r1.ll.y
0x1008 42 r1.ll.x
0x1004 9 p1.y
0x1000 42 p1.x

74 Digital Design & Computer Architecture Digital Building Blocks


Appendix C: C Programming

Memory
Odds & Ends
Passing Structures to Functions
Complex data structures and arrays are normally passed to C
programs by address rather than copied; it’s more efficient.

void createRect(int xl, int yl, int width, int height, int color, rect *r) {
r->ll.x = x1; r->ll.y = yl;
r->ur.x = xl + width; r->ur.y = yl + height;
r->color = color;
}

int main(void) {
rect r1;
createRect(3, 5, 10, 20, 1, &r1);
}

76 Digital Design & Computer Architecture Digital Building Blocks


Multidimensional Arrays
Address0 Entry
0x1068 field[1][2][2]
• Stored in consecutive addresses 0x1060 field[1][2][1]
0x1068 field[1][2][0]
– last dimension first 0x1060 field[1][1][2]
0x1068 field[1][1][1]
0x1060 field[1][1][0]

double field[2][3][3]; 0x1068


0x1060
field[1][0][2]
field[1][0][1]
0x1068 field[1][0][0]
0x1060 field[0][2][2]
0x1068 field[0][2][1]
0x1060 field[0][2][0]
0x1068 field[0][1][2]
0x1060 field[0][1][1]
0x1058 field[0][1][0]
0x1050 field[0][0][2]
0x1048 field[0][0][1]
0x1040 field[0][0][0]

77 Digital Design & Computer Architecture Digital Building Blocks


Complex Structures in Memory
Address Entry
0x277E z[9].s[15]
typedef struct foo {
.. …
double d[4][5]; 0x217E z[1][s[15]

unsigned short s[16]; .. …


0x20C0 z[1].d[0][0]
} foo; 0x20BE z[0].s[15]
… …
0x20A2 z[0].s[1]
foo z[10]; 0x20A0 z[0].s[0]
int s5 = sizeof(z[0]); 0x2098 z[0].d[3][4]
… …
// 8*4*5 + 2*16 = 192 = 0xC0
0x2008 z[0].d[0][1]
int s5 = sizeof(z); 0x2000 z[0].d[0][0]

// 10*192 = 1920 = 0x780

78 Digital Design & Computer Architecture Digital Building Blocks


Appendix C: C Programming

Dynamic
Memory
Allocation
Memory Allocation
• malloc returns a pointer to allocated memory of a
certain number of bytes.
• free frees this memory.
• These functions are declared in stdlib

• int *ary = (int*)malloc(10*sizeof(int));

80 Digital Design & Computer Architecture Digital Building Blocks


Example: Variable Sized Arrays
• In standard C, multidimensional array sizes must be
declared at compile time.
• Treat variable-sized M row x N column array as 1-
dimensional array of M x N entries

81 Digital Design & Computer Architecture Digital Building Blocks


Variable Dimension Matrix Example
#include <stdlib.h> // for malloc

double* newMatrix(int m, int n) {


double *mat;

mat = (double*)malloc(m*n*sizeof(double));
return mat;
}

double* newIdentityMatrix(int n) {
double *mat = newMatrix(n, n);
int i, j;

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


for (j=0; j<n; j++)
mat[j+i*n] = (i==j);
return mat;
}

82 Digital Design & Computer Architecture Digital Building Blocks


Variable Dimension Matrix Example
void scaleMatrix(double *mat, double *scaled, int m, int n, double c) {
int i, j;

for (i=0; i<m; i++)


for (j=0; j<n; j++)
scaled[j+i*n] = mat[j+i*n]*c;
}

int main(void) {
double *m1, *m2;

m1 = newIdentityMatrix(3);
m2 = newMatrix(3, 3);
scaleMatrix(m1, m2, 3, 3, 10);
free(m1);
}

83 Digital Design & Computer Architecture Digital Building Blocks


About these Notes
Digital Design and Computer Architecture Lecture Notes
© 2020 Sarah Harris and David Harris

These notes may be used and modified for educational and/or


non-commercial purposes so long as the source is attributed.

84 Digital Design & Computer Architecture Digital Building Blocks

You might also like