https://github.com/sebastian-nunez/systems-programming
https://github.com/sebastian-nunez/systems-programming
bash c operating-system system-programming unix
Last synced: about 1 year ago
JSON representation
- Host: GitHub
- URL: https://github.com/sebastian-nunez/systems-programming
- Owner: sebastian-nunez
- Created: 2022-08-22T13:33:59.000Z (over 3 years ago)
- Default Branch: master
- Last Pushed: 2022-11-28T15:20:06.000Z (over 3 years ago)
- Last Synced: 2025-01-21T13:13:17.786Z (about 1 year ago)
- Topics: bash, c, operating-system, system-programming, unix
- Language: C
- Homepage:
- Size: 30.4 MB
- Stars: 0
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# COP4338 - Systems Programming
## Table of Contents
- [**Chapter 0: UNIX Basics**](#chapter-0-unix-basics)
- [UNIX Cheat Sheet](#unix-cheat-sheet)
- [.vimrc](#vimrc)
- [.nanorc](#nanorc)
- [**Chapter 1: Basics, Command Line Arguments, and Makefile**](#chapter-1-basics-command-line-arguments-and-makefile)
- [Command Line Arguments (argc, argv)](#command-line-arguments-argc-argv)
- [Command Line Arguments (Validation)](#command-line-arguments-validation)
- [Command Line Arguments and Files](#command-line-arguments-and-files)
- [Macros (#define directive)](#macros-define-directive)
- [Single Step Compilation](#single-step-compilation)
- [Modular Compilation](#modular-compilation)
- [Makefiles](#makefiles)
- [Makefile (Sample)](#makefile-sample)
- [**Chapter 2: Variables, Data Types, and Random Numbers**](#chapter-2-variables-data-types-and-random-numbers)
- [Variables](#variables)
- [Variable Declaration (Integers)](#variable-declaration-integers)
- [Identifiers](#identifiers)
- [Keywords Table](#keywords-table)
- [Arithmetic Expressions](#arithmetic-expressions)
- [Precendence](#precendence)
- [Double vs Int](#double-vs-int)
- [Floating Point Numbers](#floating-point-numbers)
- [Printing Floating Point Numbers](#printing-floating-point-numbers)
- [Floating Point Division by Zero (-inf, +inf)](#floating-point-division-by-zero--inf-inf)
- [Scientific Notation](#scientific-notation)
- [Constants](#constants)
- [Math Library \](#math-library-mathh)
- [Integer Division (floor division)](#integer-division-floor-division)
- [Integer Division by Zero (NaN, Undefined)](#integer-division-by-zero-nan-undefined)
- [Modulo (%)](#modulo-)
- [Extracting Digits (%, /)](#extracting-digits--)
- [Random Numbers in Range (%)](#random-numbers-in-range-)
- [Type Conversions](#type-conversions)
- [Type Casting](#type-casting)
- [Binary](#binary)
- [ASCII Table](#ascii-table)
- [Character Data Type](#character-data-type)
- [Strings](#strings)
- [Strings as Character Arrays - char\[\]](#strings-as-character-arrays---char)
- [Scanf and Whitespace](#scanf-and-whitespace)
- [Integer Overflow](#integer-overflow)
- [Numeric Data Types](#numeric-data-types)
- [Floating Point Data Types](#floating-point-data-types)
- [Unsigned Data Types](#unsigned-data-types)
- [Random Numbers \ and \](#random-numbers-stdlibh-and-timeh)
- [Format Specifier Table \](#format-specifier-table-stdioh)
- [Input using Scanf (I/O)](#input-using-scanf-io)
- [**Chapter 3: Control Flow and String Manipulation**](#chapter-3-control-flow-and-string-manipulation)
- [Control Statements (if, else, else if)](#control-statements-if-else-else-if)
- [Equality Operator (==)](#equality-operator-)
- [Integer, Character and Floating Point Equality](#integer-character-and-floating-point-equality)
- [Relational Operators (\<, \>, \<=,\>=)](#relational-operators---)
- [Logical Operators (\&\&, ||, !)](#logical-operators---)
- [Bitwise Operators (\&, |, \<\<, \>\>)](#bitwise-operators----)
- [Order of Evaluation](#order-of-evaluation)
- [Switch Case Statement](#switch-case-statement)
- [Boolean Data Type \](#boolean-data-type-stdboolh)
- [String Comparison (strcmp)](#string-comparison-strcmp)
- [String Indexing](#string-indexing)
- [String Methods \](#string-methods-stringh)
- [Character Operations \](#character-operations-ctypeh)
- [Ternary Operator (?)](#ternary-operator-)
- [Floating Point Comparison (delta)](#floating-point-comparison-delta)
- [Short Circuit Evaluation](#short-circuit-evaluation)
- [**Chapter 4: Loops, Scope and Enums**](#chapter-4-loops-scope-and-enums)
- [While Loops](#while-loops)
- [For Loops](#for-loops)
- [Pre vs Post Operators](#pre-vs-post-operators)
- [Do-While Loops](#do-while-loops)
- [Loops and Strings](#loops-and-strings)
- [Nested Loops](#nested-loops)
- [Break Statement](#break-statement)
- [Continue Statement](#continue-statement)
- [Loop Indexing](#loop-indexing)
- [Variable Scope](#variable-scope)
- [Enums](#enums)
- [Enums Example](#enums-example)
- [**Chapter 5: Arrays and Strings**](#chapter-5-arrays-and-strings)
- [General Concept](#general-concept)
- [Array Declaration](#array-declaration)
- [Array Initialization](#array-initialization)
- [Array Iteration (+ Out of Bounds)](#array-iteration--out-of-bounds)
- [Multiple Arrays](#multiple-arrays)
- [Swapping Values](#swapping-values)
- [2D Arrays](#2d-arrays)
- [Character Arrays](#character-arrays)
- [String Library \](#string-library-stringh)
- [I/O: scanf vs fgets \](#io-scanf-vs-fgets-stdioh)
- [Type Checking and Conversion \](#type-checking-and-conversion-ctypeh)
- [Arrays and Strings (Example)](#arrays-and-strings-example)
- [Annual Salary (Example)](#annual-salary-example)
- [**Chapter 6: Functions**](#chapter-6-functions)
- [Basics](#basics)
- [Parameters](#parameters)
- [Void Functions](#void-functions)
- [Modular Development](#modular-development)
- [Modular Math Expressions](#modular-math-expressions)
- [Unit Testing](#unit-testing)
- [Assertions (Unit Testing) ](#assertions-unit-testing-asserth)
- [How Functions Work](#how-functions-work)
- [Pass by Value](#pass-by-value)
- [Pass by Pointer/Reference](#pass-by-pointerreference)
- [Functions with Array Parameters](#functions-with-array-parameters)
- [Const and Array Parameters](#const-and-array-parameters)
- [Strings as Parameters](#strings-as-parameters)
- [Function Protope/Declaration](#function-protopedeclaration)
- [Variable Scope (Functions)](#variable-scope-functions)
- [Preprocessor and Include](#preprocessor-and-include)
- [Header Guards](#header-guards)
- [Separate Files](#separate-files)
- [**Chapter 7: Structs**](#chapter-7-structs)
- [Defining Structs and Typedef](#defining-structs-and-typedef)
- [Returning Structs from Functions](#returning-structs-from-functions)
- [Structs and Arrays](#structs-and-arrays)
- [Structs, Arrays, and Functions (Example)](#structs-arrays-and-functions-example)
- [Derefencing a Pointer to a Struct (->)](#derefencing-a-pointer-to-a-struct--)
- [Seperate Files for Structs](#seperate-files-for-structs)
- [**Chapter 8: Pointers**](#chapter-8-pointers)
- [Why Pointers](#why-pointers)
- [Pointer Basics](#pointer-basics)
- [Dereferencing a Pointer](#dereferencing-a-pointer)
- [Null Pointer](#null-pointer)
- [Common Pointer Mistakes](#common-pointer-mistakes)
- [**Malloc Function**](#malloc-function)
- [**Free Function**](#free-function)
- [Pointers with Structs](#pointers-with-structs)
- [String Functions with Pointers](#string-functions-with-pointers)
- [String Searching Methods (Table)](#string-searching-methods-table)
- [Malloc for Arrays and Strings](#malloc-for-arrays-and-strings)
- [Dynamic Copy of a String](#dynamic-copy-of-a-string)
- [**Realloc Function**](#realloc-function)
- [Dynamically Reallocating Size of an Array (Code)](#dynamically-reallocating-size-of-an-array-code)
- [**Vector ADT**](#vector-adt)
- [vector.h](#vectorh)
- [Vector Implementation](#vector-implementation)
- [**Vector Functions (Table)**](#vector-functions-table)
- [Segmentation Fault](#segmentation-fault)
- [LinkedList vs. Vector](#linkedlist-vs-vector)
- [LinkedList (Code)](#linkedlist-code)
- [**Memory Regions - Heap and Stack (Table)**](#memory-regions---heap-and-stack-table)
- [Memory Leaks](#memory-leaks)
- [**Chapter 9: Input and Output**](#chapter-9-input-and-output)
- [File Pointer: stdout (fprintf)](#file-pointer-stdout-fprintf)
- [File Pointer: stdin (fscanf)](#file-pointer-stdin-fscanf)
- [Formatted Output (Table)](#formatted-output-table)
- [Integer Formatting](#integer-formatting)
- [String Formatting](#string-formatting)
- [Flushing Output (fflush)](#flushing-output-fflush)
- [**Input Parsing**](#input-parsing)
- [Input Validation](#input-validation)
- [Parsing Input String (sscanf)](#parsing-input-string-sscanf)
- [Parsing Input (sscanf and fgets) Example](#parsing-input-sscanf-and-fgets-example)
- [**File Input and Output**](#file-input-and-output)
- [**Writting to Files (fopen)**](#writting-to-files-fopen)
- [**Parsing Through an Entire File (!feof)**](#parsing-through-an-entire-file-feof)
- [Binary Files](#binary-files)
- [Writting to a Binary Files](#writting-to-a-binary-files)
- [Reading from a Binary File](#reading-from-a-binary-file)
## Chapter 0: UNIX Basics
### UNIX Cheat Sheet

## .vimrc
```vim
""set background=dark
""set termguicolors
""colorscheme fleet2
syntax on
set number
set expandtab
set tabstop=4
set shiftwidth=4
set ignorecase
set smarttab
set smartcase
""set showmatch
set history=500
set lbr
set tw=500
set ai "Auto Indent"
set wrap "Wrap Lines"
set hlsearch
set lazyredraw
set magic
set wildmenu
" Ignore compiled files
set wildignore=*.o,*~,*.pyc
if has("win16") || has("win32")
set wildignore+=.git\*,.hg\*,.svn\*
else
set wildignore+=*/.git/*,*/.hg/*,*/.svn/*,*/.DS_Store
endif
" Set to auto read when a file is changed from the outside
set autoread
au FocusGained,BufEnter * checktime
" Configure backspace so it acts as it should act
set backspace=eol,start,indent
set whichwrap+=<,>,h,l
" Enable filetype plugins
filetype on
filetype plugin on
filetype indent on
" in makefiles, don't expand tabs to spaces, since actual tab characters are
" needed, and have indentation at 8 chars to be sure that all indents are tabs
" (despite the mappings later):
autocmd FileType make set noexpandtab shiftwidth=8 softtabstop=0
" for C-like programming where comments have explicit end
" characters, if starting a new line in the middle of a comment automatically
" insert the comment leader characters:
autocmd FileType c,cpp,java set formatoptions+=ro
autocmd FileType c set omnifunc=ccomplete#Complete
" add completion for xHTML
autocmd FileType xhtml,html set omnifunc=htmlcomplete#CompleteTags
" Return to last edit position when opening files (You want this!)
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
" Delete trailing white space on save, useful for some filetypes ;)
fun! CleanExtraSpaces()
let save_cursor = getpos(".")
let old_query = getreg('/')
silent! %s/\s\+$//e
call setpos('.', save_cursor)
call setreg('/', old_query)
endfun
inoremap { {}ha
inoremap ( ()ha
inoremap [ []ha
inoremap " ""ha
inoremap ' ''ha
inoremap ` ``ha
" Output the current syntax group
nnoremap :echo "hi<" . synIDattr(synID(line("."),col("."),1),"name") . '> trans<'
\ . synIDattr(synID(line("."),col("."),0),"name") . "> lo<"
\ . synIDattr(synIDtrans(synID(line("."),col("."),1)),"name") . ">"
```
### .nanorc
```vim
set atblanks # wrap line at blanks.
set softwrap # Enable softwrap of lines.
set tabsize 4 # Sets tab-to-spaces size to 4.
set tabstospaces # Converts TAB key press to spaces.
set linenumbers # Lines are numbered.
set casesensitive # Case insensitive search.
set historylog # Save the last 100 history searches for later use.
set positionlog # Saves the cursor position between editing sessions.
set autoindent # A new line will have the same number of leading spaces as the previous one.
set brackets ""')>]}"
set matchbrackets "(<[{)>]}"
set smooth
```
[Back to top](#table-of-contents)
## Chapter 1: Basics, Command Line Arguments, and Makefile
### Command Line Arguments (argc, argv)

### Command Line Arguments (Validation)
.png>)
### Command Line Arguments and Files

### Macros (#define directive)
.png>)
### Single Step Compilation

[Back to top](#table-of-contents)
### Modular Compilation

### Makefiles

### Makefile (Sample)

[Back to top](#table-of-contents)
## Chapter 2: Variables, Data Types, and Random Numbers
### Variables

### Variable Declaration (Integers)
.png>)
### Identifiers

### Keywords Table

[Back to top](#table-of-contents)
### Arithmetic Expressions

### Precendence

### Double vs Int

### Floating Point Numbers

### Printing Floating Point Numbers

### Floating Point Division by Zero (-inf, +inf)

[Back to top](#table-of-contents)
### Scientific Notation

### Constants

### Math Library

### Integer Division (floor division)

### Integer Division by Zero (NaN, Undefined)

### Modulo (%)

### Extracting Digits (%, /)

### Random Numbers in Range (%)

### Type Conversions

### Type Casting
[Back to top](#table-of-contents)

### Binary

### ASCII Table

### Character Data Type

### Strings

### Strings as Character Arrays - char[]
![Strings as Character Arrays - char[]](./images/2.15%20String%20as%20char%5B%5D.png)
### Scanf and Whitespace

### Integer Overflow


[Back to top](#table-of-contents)
### Numeric Data Types

### Floating Point Data Types

### Unsigned Data Types

### Random Numbers and

### Format Specifier Table

### Input using Scanf (I/O)
[Back to top](#table-of-contents)

[Back to top](#table-of-contents)
## Chapter 3: Control Flow and String Manipulation
### Control Statements (if, else, else if)

### Equality Operator (==)

### Integer, Character and Floating Point Equality
.png>)
### Relational Operators (<, >, <=,>=)
[Back to top](#table-of-contents)

### Logical Operators (&&, ||, !)

.png>)
### Bitwise Operators (&, |, <<, >>)

### Order of Evaluation

[Back to top](#table-of-contents)
### Switch Case Statement

.png>)
### Boolean Data Type

### String Comparison (strcmp)
.png>)

### String Indexing

### String Methods

[Back to top](#table-of-contents)
### Character Operations

### Ternary Operator (?)
.png>)
## Floating Point Comparison (delta)
.png>)
[Back to top](#table-of-contents)
### Short Circuit Evaluation

[Back to top](#table-of-contents)
## Chapter 4: Loops, Scope and Enums
### While Loops

### For Loops


[Back to top](#table-of-contents)
### Pre vs Post Operators

### Do-While Loops

### Loops and Strings

### Nested Loops

[Back to top](#table-of-contents)
### Break Statement

### Continue Statement

### Loop Indexing

[Back to top](#table-of-contents)
### Variable Scope

### Enums

### Enums Example

```c
#include
/* Manual controller for traffic light */
int main(void) {
enum LightState { LS_RED,
LS_GREEN,
LS_YELLOW,
LS_DONE };
enum LightState lightVal;
char userCmd;
lightVal = LS_RED;
userCmd = '-';
printf("User commands: n (next), r (red), q (quit).\n\n");
lightVal = LS_RED;
while (lightVal != LS_DONE) {
if (lightVal == LS_GREEN) {
printf("Green light ");
scanf(" %c", &userCmd);
if (userCmd == 'n') { // Next
lightVal = LS_YELLOW;
}
} else if (lightVal == LS_YELLOW) {
printf("Yellow light ");
scanf(" %c", &userCmd);
if (userCmd == 'n') { // Next
lightVal = LS_RED;
}
} else if (lightVal == LS_RED) {
printf("Red light ");
scanf(" %c", &userCmd);
if (userCmd == 'n') { // Next
lightVal = LS_GREEN;
}
}
if (userCmd == 'r') { // Force immediate red
lightVal = LS_RED;
} else if (userCmd == 'q') { // Quit
lightVal = LS_DONE;
}
}
printf("Quit program.\n");
return 0;
}
```
[Back to top](#table-of-contents)
## Chapter 5: Arrays and Strings
### General Concept

### Array Declaration

### Array Initialization

### Array Iteration (+ Out of Bounds)


### Multiple Arrays

[Back to top](#table-of-contents)
### Swapping Values

### 2D Arrays

### Character Arrays

.png>)
### String Library


### I/O: scanf vs fgets
.png>)
[Back to top](#table-of-contents)
### Type Checking and Conversion


### Arrays and Strings (Example)

### Annual Salary (Example)

```c
#include
#include
int main(void) {
const int BASE_TABLE_ELEMENTS = 5;
const int MAX_ELEMENTS = 10;
int annualSalary;
double taxRate;
int taxToPay;
int totalSalaries;
int totalTaxes;
int numSalaries;
bool keepLooking;
int i;
int salaryBase[] = {20000, 50000, 100000, 999999999};
double taxBase[] = {.10, .20, .30, .40};
int annualSalaries[MAX_ELEMENTS];
int taxesToPay[MAX_ELEMENTS];
numSalaries = 0;
printf("\nEnter annual salary (0 to exit): \n");
scanf("%d", &annualSalary);
while ((annualSalary > 0) && (numSalaries < MAX_ELEMENTS)) {
i = 0;
taxRate = 0;
keepLooking = true;
// Search for appropriate table row for given annualSalary
while ((i < BASE_TABLE_ELEMENTS) && keepLooking) {
if (annualSalary <= salaryBase[i]) {
taxRate = taxBase[i];
keepLooking = false;
} else {
++i;
}
} // End inner while loop (search for appropriate table row)
taxToPay = (int)(annualSalary * taxRate); // Truncate tax to an integer amount
annualSalaries[numSalaries] = annualSalary;
taxesToPay[numSalaries] = taxToPay;
printf("Annual salary: %d", annualSalaries[numSalaries]);
printf("\tTax rate: %lf", taxRate);
printf("\tTax to pay: %d\n", taxesToPay[numSalaries]);
++numSalaries;
// Get the next annual salary
printf("\nEnter annual salary (0 to exit): \n");
scanf("%d", &annualSalary);
} // End outer while loop (valid annualSalary entered)
// Sum the annual salaries and taxes to pay and print the totals
totalSalaries = 0;
totalTaxes = 0;
for (i = 0; i < numSalaries; ++i) {
totalSalaries += annualSalaries[i];
totalTaxes += taxesToPay[i];
}
printf("\nTotal salaries: %d", totalSalaries);
printf("\tTotal taxes: %d\n", totalTaxes);
return 0;
}
```
[Back to top](#table-of-contents)
## Chapter 6: Functions
### Basics

### Parameters


### Void Functions

### Modular Development

### Modular Math Expressions

[Back to top](#table-of-contents)
### Unit Testing

### Assertions (Unit Testing)

### How Functions Work

### Pass by Value

### Pass by Pointer/Reference

[Back to top](#table-of-contents)
### Functions with Array Parameters

### Const and Array Parameters

### Strings as Parameters

### Function Protope/Declaration
[Back to top](#table-of-contents)

### Variable Scope (Functions)

### Preprocessor and Include

### Header Guards

### Separate Files

[Back to top](#table-of-contents)
## **Chapter 7: Structs**
- [**Chapter 7: Structs**](#chapter-7-structs)
- [Defining Structs and Typedef](#defining-structs-and-typedef)
- [Returning Structs from Functions](#returning-structs-from-functions)
- [Structs and Arrays](#structs-and-arrays)
- [Structs, Arrays, and Functions (Example)](#structs-arrays-and-functions-example)
- [Seperate Files for Structs](#seperate-files-for-structs)
### Defining Structs and Typedef

### Returning Structs from Functions

### Structs and Arrays

### Structs, Arrays, and Functions (Example)
A programmer commonly uses structs, arrays, and functions together. Consider a program that allows a reservations agent to reserve seats for people, useful for a theater, an airplane, etc. The below program defines a Seat struct whose data members are a person's first name, last name, and the amount paid for the seat. The program declares an array of 5 seats to represent the theater, airplane, etc., initializes all seats to being empty (indicated by a first name of "empty"), and then allows a user to enter commands to print all seats, reserve a seat, or quit.
```c
#include
#include
#include
typedef struct Seat_struct {
char firstName[50];
char lastName[50];
int amountPaid;
} Seat;
/*** Functions for Seat ***/
void SeatMakeEmpty(Seat* seat) {
strcpy((*seat).firstName, "empty");
strcpy((*seat).lastName, "empty");
(*seat).amountPaid = 0;
}
bool SeatIsEmpty(Seat seat) {
return (strcmp(seat.firstName, "empty") == 0);
}
void SeatPrint(Seat seat) {
printf("%s ", seat.firstName);
printf("%s, ", seat.lastName);
printf("Paid: %d\n", seat.amountPaid);
}
/*** End functions for Seat ***/
/*** Functions for array of Seat ***/
void SeatsMakeEmpty(Seat seats[], int numSeats) {
int i;
for (i = 0; i < numSeats; ++i) {
SeatMakeEmpty(&seats[i]);
}
}
void SeatsPrint(Seat seats[], int numSeats) {
int i;
for (i = 0; i < numSeats; ++i) {
printf("%d: ", i);
SeatPrint(seats[i]);
}
}
/*** End functions for array of Seat ***/
int main(void) {
const int NUM_SEATS = 5;
char userKey;
int seatNum;
Seat allSeats[NUM_SEATS];
Seat currSeat;
userKey = '-';
SeatsMakeEmpty(allSeats, NUM_SEATS);
while (userKey != 'q') {
printf("Enter command (p/r/q): ");
scanf(" %c", &userKey);
if (userKey == 'p') { // Print seats
SeatsPrint(allSeats, NUM_SEATS);
printf("\n");
} else if (userKey == 'r') { // Reserve seat
printf("Enter seat num: ");
scanf("%d", &seatNum);
if (!SeatIsEmpty(allSeats[seatNum])) {
printf("Seat not empty.\n\n");
} else {
printf("Enter first name: ");
scanf("%s", currSeat.firstName);
printf("Enter last name: ");
scanf("%s", currSeat.lastName);
printf("Enter amount paid: ");
scanf("%d", &currSeat.amountPaid);
allSeats[seatNum] = currSeat;
printf("Completed.\n\n");
}
}
// FIXME: Add option to delete reservations
else if (userKey == 'q') { // Quit
printf("Quitting.\n");
} else {
printf("Invalid command.\n\n");
}
}
return 0;
}
```
### Derefencing a Pointer to a Struct (->)

### Seperate Files for Structs

## Chapter 8: Pointers
### Why Pointers

### Pointer Basics

[Back to top](#table-of-contents)
### Dereferencing a Pointer

### Null Pointer

### Common Pointer Mistakes

### **Malloc Function**

### **Free Function**

### Pointers with Structs

[Back to top](#table-of-contents)
### String Functions with Pointers

### String Searching Methods (Table)
.png>)
### Malloc for Arrays and Strings

### Dynamic Copy of a String

- Make sure to account of the NULL character terminator in the String Length
[Back to top](#table-of-contents)
### Realloc Function

#### Dynamically Reallocating Size of an Array (Code)
```c
#include
#include
int main(void) {
int* userVals = NULL; // No array yet
int numVals;
int i;
char userInput;
int userValsSum;
double userValsAvg;
userInput = 'c';
while (userInput == 'c') {
printf("Enter number of integer values: ");
scanf(" %d", &numVals);
if (userVals == NULL) {
userVals = (int*)malloc(numVals * sizeof(int));
}
else {
userVals = (int*)realloc(userVals, numVals * sizeof(int));
}
printf("Enter %d integer values...\n", numVals);
for (i = 0; i < numVals; ++i) {
printf("Value: ");
scanf("%d", &(userVals[i]));
}
// Calculate average
userValsSum = 0;
for (i = 0; i < numVals; ++i) {
userValsSum = userValsSum + userVals[i];
}
userValsAvg = (double)userValsSum / (double)numVals;
printf("Average = %lf\n", userValsAvg);
printf("\nEnter 'c' to compute another average (any other key to quit): ");
scanf(" %c", &userInput);
}
free(userVals);
return 0;
}
```
[Back to top](#table-of-contents)
### **Vector ADT**

#### vector.h
```c
#ifndef VECTOR_H
#define VECTOR_H
// struct and typedef declaration for Vector ADT
typedef struct vector_struct {
int* data;
unsigned int size;
} vector;
// interface for accessing Vector ADT
// Initialize vector
void vector_create(vector* v, unsigned int vectorSize);
// Destroy vector
void vector_destroy(vector* v);
// Resize the size of the vector
void vector_resize(vector* v, unsigned int vectorSize);
// Return pointer to element at specified index
int* vector_get(vector* v, unsigned int index);
// Insert new value at specified index
void vector_insert(vector* v, unsigned int index, int value);
// Insert new value at end of vector
void vector_push_back(vector* v, int value);
// Erase (remove) value at specified index
void vector_remove(vector* v, unsigned int index);
// Return number of elements within vector
int vector_size(vector* v);
#endif
```
[Back to top](#table-of-contents)
#### Vector Implementation
```c
#include "vector.h"
#include
#include
int main(void) {
vector v;
vector_create(&v, 4);
*vector_get(&v, 0) = 27;
*vector_get(&v, 1) = 44;
*vector_get(&v, 2) = 9;
*vector_get(&v, 3) = 17;
vector_remove(&v, 1);
vector_remove(&v, 0);
vector_insert(&v, 0, 88);
vector_pop(&v);
printf("Contents:\n");
for (int i = 0; i < vector_size(&v); ++i) {
printf("%d\n", *vector_get(&v, i));
}
vector_destroy(&v);
return 0;
}
// Initialize vector with specified size
void vector_create(vector* v, unsigned int vectorSize) {
if (v == NULL)
return;
v->data = (int*)malloc(vectorSize * sizeof(int));
v->size = vectorSize;
for (int i = 0; i < v->size; ++i) {
v->data[i] = 0;
}
}
// Destroy vector
void vector_destroy(vector* v) {
if (v == NULL)
return;
free(v->data);
v->data = NULL;
v->size = 0;
}
// Resize the size of the vector
void vector_resize(vector* v, unsigned int vectorSize) {
if (v == NULL)
return;
int oldSize = v->size;
v->data = (int*)realloc(v->data, vectorSize * sizeof(int));
v->size = vectorSize;
for (int i = oldSize; i < v->size; ++i) {
v->data[i] = 0;
}
}
// Return pointer to element at specified index
int* vector_get(vector* v, unsigned int index) {
if (v == NULL || index >= v->size)
return NULL;
return &(v->data[index]);
}
// Insert new value at specified index
void vector_insert(vector* v, unsigned int index, int value) {
if (v == NULL || index > v->size)
return;
vector_resize(v, v->size + 1);
for (int i = v->size - 1; i > index; --i) {
v->data[i] = v->data[i - 1];
}
v->data[index] = value;
}
// Insert new value at end of vector
void vector_push_back(vector* v, int value) {
vector_insert(v, v->size, value);
}
// Remove value at specified index
void vector_remove(vector* v, unsigned int index) {
if (v == NULL || index >= v->size)
return;
for (int i = index; i < v->size - 1; ++i) {
v->data[i] = v->data[i + 1];
}
vector_resize(v, v->size - 1);
}
// Remove value at the last element
void vector_pop(vector* v) {
if (v == NULL)
return;
vector_remove(v, v->size - 1);
}
// Return number of elements within vector
int vector_size(vector* v) {
if (v == NULL)
return -1;
return v->size;
}
```
#### **Vector Functions (Table)**
.png>)
#### Segmentation Fault

### LinkedList vs. Vector

[Back to top](#table-of-contents)
#### LinkedList (Code)
```c
#include
#include
typedef struct IntNode_struct {
int dataVal;
struct IntNode_struct* nextNodePtr;
} IntNode;
// Constructor
void IntNode_Create(IntNode* thisNode, int dataInit, IntNode* nextLoc) {
thisNode->dataVal = dataInit;
thisNode->nextNodePtr = nextLoc;
}
/* Insert newNode after node.
Before: thisNode -- next
After: thisNode -- newNode -- next
*/
void IntNode_InsertAfter(IntNode* thisNode, IntNode* newNode) {
IntNode* tmpNext = NULL;
tmpNext = thisNode->nextNodePtr; // Remember next
thisNode->nextNodePtr = newNode; // this -- new -- ?
newNode->nextNodePtr = tmpNext; // this -- new -- next
}
// Print dataVal
void IntNode_PrintNodeData(IntNode* thisNode) {
printf("%d\n", thisNode->dataVal);
}
// Grab location pointed by nextNodePtr
IntNode* IntNode_GetNext(IntNode* thisNode) {
return thisNode->nextNodePtr;
}
int main(void) {
IntNode* headObj = NULL; // Create IntNode objects
IntNode* nodeObj1 = NULL;
IntNode* nodeObj2 = NULL;
IntNode* nodeObj3 = NULL;
IntNode* currObj = NULL;
// Front of nodes list
headObj = (IntNode*)malloc(sizeof(IntNode));
IntNode_Create(headObj, -1, NULL);
// Insert nodes
nodeObj1 = (IntNode*)malloc(sizeof(IntNode));
IntNode_Create(nodeObj1, 555, NULL);
IntNode_InsertAfter(headObj, nodeObj1);
nodeObj2 = (IntNode*)malloc(sizeof(IntNode));
IntNode_Create(nodeObj2, 999, NULL);
IntNode_InsertAfter(nodeObj1, nodeObj2);
nodeObj3 = (IntNode*)malloc(sizeof(IntNode));
IntNode_Create(nodeObj3, 777, NULL);
IntNode_InsertAfter(nodeObj1, nodeObj3);
// Print linked list
currObj = headObj;
while (currObj != NULL) {
IntNode_PrintNodeData(currObj);
currObj = IntNode_GetNext(currObj);
}
return 0;
}
```
### **Memory Regions - Heap and Stack (Table)**
.png>)
### Memory Leaks

[Back to top](#table-of-contents)
## **Chapter 9: Input and Output**
### File Pointer: stdout (fprintf)

### File Pointer: stdin (fscanf)

### Formatted Output (Table)

#### Integer Formatting

[Back to top](#table-of-contents)
#### String Formatting

### Flushing Output (fflush)

### **Input Parsing**

#### Input Validation

[Back to top](#table-of-contents)
### Parsing Input String (sscanf)
.png>)
#### Parsing Input (sscanf and fgets) Example

### **File Input and Output**

#### **Writting to Files (fopen)**

[Back to top](#table-of-contents)
### **Parsing Through an Entire File (!feof)**
.png>)
### Binary Files

#### Writting to a Binary Files

#### Reading from a Binary File

[Back to top](#table-of-contents)