C family Flashcards
Why can C be referred to as being almost a portable assembly language
It is as close to the machine as possible while it is almost universally available for existing processor architectures.
What does the statement “C is imperative” mean?
It describes computation in terms of statements that change a program state
What does the statement “C is declarative” mean?
describes computation in terms of what it should accomplish
C is a procedural/functional language
What does the statement “C is weakly typed” mean?
C supports implicit type conversion
What does the statement “C is statically typed” mean?
Types are checked before runtime so variables must be declared
What are compiler directives and some examples?
Special instructions that guide the preprocessor
#include will include the contents of another file - usually containing function prototypes and variable declarations
What is the difference between float, double and long double
While they are both floating point numbers, double is larger and long double is larger still
How much memory does a char, short int, int and long int take up?
char - 1 byte
short int - 2 bytes
int - 4 bytes
long int - 8 bytes
(unsigned versions take up the same amount of memory)
To what precision can a float, double and long double hold data and how much memory do they take up?
Float, 6 digits, 4 bytes
double, 15 digits, 8 bytes
long double, 18 digits, 16 bytes
As there is no boolean datatypes in ANSI C, how are conditions evaluated?
0 is considered false while any other value is considered true
How can i create AND and OR conditional statements
Double ampersand for AND: &&
Double straight liney thing for OR: ||
What is an advantage and disadvantage of using code short-hands
Adv: reduce time to type - may reduce codesize
DisAdv: do not execute any faster and may make code harder to follow
What do break and continue statements do?
Break will break out of the loop and jump to the next command
Continue will jump to the start of next iteration
What is the difference between a While and a Do While loop?
While loop will check the condition before executing
Do While will execute once before checking the condition is true
What does “pass by value” mean for functions in C
The value of the variable is passed into the function and the value can be used in further calculations. The value of the original variable is not changed
f(variable_name)
What does “pass by reference” mean for functions in C
A pointer to the variable is passed to the function, that way processing can be done on the variable and it’s actual value will change
f(*variable_name)
How can we get around C’s functions only being able to return one value if we want to change multilpe
Through the use of pointers, if multiple pointers are fed into the function then the values of multiple variables can be changed
How should we pass arguments into the main function from the command line?
It must be defined like this:
int main(int argc, char **argv)
Arg c contains the number of arguments passed and argv is an array of string values. This is not required but is suggested heavily by convention
What are the values of argv if the program is called myProgram
myProgram Hello 3 “a short sentence”
argv[0] = myProgram
argv[1] = Hello
argv[2] = 3
argv[3] = a short sentence
What are two advantages to using pointers to functions?
Functions can be passed as arguments to other functions, oft called callback functions
We can choose which function to execute at runtime based on user inputs
There’s something about qSort on lecture 3 but cba to figure it out
How are arrays stored in memory?
Arrays are stored contiguously in memory, when an array is initialized an appropriate amount of memory will be reserved
How are strings stored in C and what does it mean for a string to be unitialised?
A string is stored contiguously as an array of characters, ending in a NULL terminating character ‘\0’.
An string is uninitialized if it hasn’t had characters assinged to it and will contain random stuff until it does
What is a null terminator and what will happen if one does not exist?
The null terminator (‘\0’) tells printf when to stop printing out characters
If your string does not have a null terminator, printf carries on plodding through memory and printing out characters until it encounters one.
What will these print statements output?
char name [21] = “Elephants”;
printf(“%s\n”, name);
printf(“%20s\n”, name);
printf(“%-20s\n”, name);
printf(“%3s\n”, name);
printf(“%-20.3s\n”, name);
They will output:
Elephants
- Elephants*
*Elephants *
Elephants
*Ele *
Does the strlen function return the length of a string with or without the null terminator?
It will return it without
what does strcpy(fullName, firstname) do ?
this will copy the string held in fullName into firstName
What will strcat(str1, str2) do?
will concatonate str2 onto the end of str1, overwriting str1
How does strcmp(str, str2) work?
This function will return 0 if the two strings are the same, if otherwise it will return another int value
What will this statement do?
sprintf(fullName, “%s %s”, fullName, lastName)
Works very similar to a printf statement but the output of the printf is stored in fullName
What is a uniform random number distribution?
A distribution where all values in a defined range are equally likely
Why can we not use rand() for statistical modelling?
It does not produce high quality randomness and it not suitable for statistical modelling.
It is okay to use if a program just needs a bit of randomness
How does seeding work in C and how can srand statements be used?
Seeding refers to the process of initializing a pseudo-random number generator. Without seeding, a rand() will always start from the same internal state, leading to the same sequence of “random” numbers every time you run the program.
Seeding is can be a user inputted number but time is often recommended
used like:
srand(43);
srand(time(0));
The second option is the only one that will produce a different number each run
What does scanf do?
Will capture a user input which can then be stored
What is a stream?
It’s an abstraction of a file - this means that a consistent interface can be provided to the programmer
stdio.h much be included
What does it mean that a stream is buffered?
Data is not necessarily written to the device when the write command is issued, however this can be forced by flushing the stream
What are the two types of stream?
Text stream - sequence of characters - character translation may occur
binary stream - sequence of bytes - character translation will not occur
What are three common functions used to write to a stream - including binary streams
putc() or fputc(ch, fp) - will write a character to a stream
fputs(str, fp) - write a string to the stream
fwrite() - writes to a binary stream
What are three common functions used to read from a stream?
getc() or fgetc(fp) - read a character from a stream and can store it in a variable
fgets(str, count, fp) - read a string from a stream up to a max of count characters and stores it in str
fread() - read from a binary stream
When reading/writing to a stream what is something that must always be tested?
You must always test that opening the file was successful
What do these file modes mean?
r
w
a
rb
wb
read
write
appending to
read a binary file
write to a binary file
What does fprintf() do?
Works like a printf statement but will ouput the string to the file pointed to by fo
fprintf(fp, “String stuff %s”, ch)
what does fscanf do?
fscanf(fp,”%d,%d”,&x,&y);
like scanf, but the string is input from the file pointed to by fp
What do the following stream functions do?
fflush(fp)
remove(“MyFile.txt”)
rewind(fp)
fflush(fp) - forces the output buffer to be written to the file
remove(“myFile.txt”) - deletes the specified file
-returns 0 on success; other integer on failure
rewind(fp) - resets the file position indicator back to the beginning of the file
What are three standard streams that all programs can use without calling fopen or fclose?
-stdin input from the keyboard
-stdout output to the terminal; normal program output
-stderr output to the terminal; error and warning messages
Where should error messages be sent and why?
You must ALWAYS send error messages to stderr and not stdout.
This is because they will now show as error messages in the terminal
How exactly does an #include statement work?
It will find the file after the # and copy it’s contents into the current position in the program
include <stdio.h></stdio.h>
What is the difference between these statements
#include “myFile.h”
<stdio.h>: search for this file using the path in which the pre-processor expects to find such files
"myFile.h": search for this file firstly in the same directory as this program, and then using the path in which the pre-processor expects to find such files
</stdio.h>
Why can using #define be dangerous
Definitions are substituted before the compiler compiles the source code so any errors introduced are hard to trace
what do these statements do?
#ifdef
#ifndef
#undef
#else
#elif
#endif
ifdef if a macro is defined
#ifndef if a macro is not defined
#undef undefine a macro
#else otherwise
#elif else if
#endif end of the #ifdef or #ifndef block
What are some strong macro conventions
Macro names should be all capitals
System macros should start with two underscores
Why might someone choose to use Macros?
Defining macros can make your code more readable
Defining macros are good for values that might change some time in the future
What are the four storage classes in C
Auto(default)
register
static
extern
What does the register storage class do?
Variable is stored in the CPU’s registers for quick access
What does the static storage class do?
The variable will continue to exist even after the block in which it is defined terminates
Value is retained between repeated calls to the same function
Scope is limited to the block in which it is defined
function is only visible within its translation unit(it’s file)
what does the extern storage class do?
The scope is global
The function is visible globally
How should we name the header (.h file)?
It should always be named after the code (*.c) file it belongs too
What are some disadvantages of C being a weakly typed language?
As errors are not checked at compile time there can be type mismatch errors during program execution
Unexpected behavior while executing
Define a function in C
A uniquely named group of program statements which accepts 0 or more arguments and will return 0 or 1 to the calling code
Note: each function in C must have a unique name
Define a procedure in C
A procedure is a function which has no return value
Why should functions be prototyped?
The (one-pass) compiler needs to know a function’s definition before it is called, and functions may appear in any order in the program module.
The functions may call each other - so there is no ordering of the function definitions that defines them before they are called
The code for the function might not be in this program module.
What information is needed to prototype a function and how is it done?
The return type, function name and parameter types are needed (parameter names are not necessary)
like:
void printArray (char []);
or
int anIntFunction ();
Why are global variables considered very bad practice
They can cause a number of issues in including:
-can make code harder to maintain and debug
-Reduced encapsulation and modularity
-Namespace pollution and conflicts
What are static variables?
They are declared using the static keyword and initialized once the function is first called. They will retain their values when they go out of scope
What is the lookup table and how does it work?
It’s used to find the data assigned to variable names, when a variable is created it’s name, type and address are assigned to the lookup table. When the variable is used the name is found in the lookup table and the memory address can be used to find the data in memory
Note: pointers are a base datatype
How can you assign the memory address of a variable to a pointer
Using the & character, &var is the location where var is stored
like this:
char ch = ‘A’;
char *p;
p = &ch;
How can a memory address be shown in a printf statement?
Using %p
How much memory does storing a pointer take?
8 bytes on windows 64, 3 on windows 32
In pointer arithmetic how many bytes are added by the statement x++
x is a pointer
2 bytes are added
char str[20] = “Hello world!”;
char *p = str;
What will this printf statement output?
printf(“p is %s\n”, p);
p is Hello World!
What is the advantage of using void pointers?
Void pointers can point to any datatype as long as it is cast before use
How could i cast a void pointer to a char?
*(char *)p
What causes these errors:
Memory fault
Segmentation fault
Memory fault: trying to access memory it is not allowed access to
Segmentation fault: trying to access memory in a way that is not allowed
What is an issue that can occur here?
char str1[20] = “Goodbye”;
char str2[6] = “Hello”;
str2[16] = ‘x’;
The program won’t throw any errors however the program could be corrupted as the memory address that would belong to str2[16] will be changed to x. If this is currently being used by another variable it will be corrupted
What are some solutions when you don’t know how much memory is needed at runtime
The best way is to dynamically allocate memory at runtime using pointers however we can also declare an array whose size is determined at runtime(potential issue is we don’t know how much free contiguous memory is available) or process the data in smaller dhunks
How could i dynamically allocate memory for an int that is 23 numbers long?
int *p = NULL;
p = (int )malloc(23sizeof(int));
Note: you must always trap the fact that memory was not allocated
What happens when a variable goes out of scope?
Its memory is released
What is a memory leak?
When allocated memory is not released even when it goes out of scope/ is not longer needed
When using malloc what must also happen?
The memory must be explicity freed
like:
free(p)
What are structures in C?
A type of variable that groups multiple related data items together
-The closest thing that C has to a class
How can i declare a structure in C?
struct <structure>
{
<variable>;
};</variable></structure>
This should be done before the function prototypes
How can new datatypes be defined using structures and the typedef command?
typedef struct bookStruct BOOK;
This can then be used as a datatype in variable declaration like:
BOOK myBook;
this is identical to
struct bookStruct myBook
What are some things that will accept a structure as a parameter
A function can accept a structure as a parameter as well as returning one
If you create a datatype using a structure then you can have arrays of them e.g.
BOOK books[20];
How can i access the parameters of a structure with and without a pointer?
Without a pointer:
structureName.parameterName
With a pointer e.g. BOOK *secondBook;
secondBook->parameterName
this saves the need for the structure to be de-referenced like:
(*secondBook).parameterName
What are some situations where a linked list would be used over an array
-When we don’t know how many elements the array needs to hold
-We don’t want to store the elements in a linear structure e.g. a tree
-You want to store elements of different datatypes
Define a linked list
A data structure containing an ordered sequence of nodes in which each node consists of data and one or more links to other nodes in the sequence.
What are some advantages of a linked list
It is a memory-efficient means of storing large data structures
It has a speed efficient means of inserting and deleting nodes
What is an advantage and two disadvantages of using arrays
With arrays you can go directly to the nth element
Disadvantages:
-insert delete operations require other elements to be moved
-if an element needs to be inserted into a full array then the array must be extended or the program will have to stop
How can i define the structure of a list node and initialize an empty list?
struct anode
{
/*this is where the data variables go e.g. */ char data; struct anode *nextNode };
typedef struct anode NODE;
NODE *root = NULL;
How can i allocate memory and add a node to a linked list?
Initialise the node:
NODE *newNode;
Allocate Memory:
if ( ( newNode = (NODE *)malloc(sizeof(NODE)) ) == NULL)
{ …}
Then set the nodes new values:
newNode->data = ‘A’;
newNode->nextNode = NULL;
then add it to the empty list:
root = newNode;
How do i add a new node to the beginning of a linked list
newNode->nextNode = root;
root = newNode;
How do i add a new node to the end of a linked list
root->nextNode = newNode;
How should i add a node in the middle of a linked list
-Find the right place to insert
-Link the new node to the tail of the list
-Link the head of the list to the new node
Should linked list nodes be in contiguous memory?
There is no need for linked nodes to be in contiguous memory
What are some advantages of linked lists?
Does not matter where each node is stored in memory
insert/delete requires only changing the values of 1/2 pointers
Size of linked list is limited only by computer memory
Lists may be linked in more than one way
What are some disadvantages of linked lists
To find an element you must start from the beginning and follow the pointer
What is the wrong way to insert a node to a linked list?
If we first link the head of the list to the new node then we have no idea how to link the tail node to the end of the list and all subsequent items in the list are lost
What must we also do for each deleted node
We must also free the memory for each node
What is a doubly linked list and why is it useful?
It’s where nodes in the list are linked in two distinct orders, for example one order could be alphabetical and one could be chronological
What are 4 common types of dynamically linked data structures
-Stacks
-queues
-circular lists
-trees
What is POSIX?
It is a family of related standards used for maintaining compatability between variants of UNIX
What does POSIX define?
It defines:
-application programming interface (API)
-command line shells
-utility interfaces
What set of services does POSIX describe?
It describes:
-an interface, written in C
-a command interpreter
-common utility programs
-standard semantics and syntax
What is the open group and when was it founded?
Established in 1995
It aims to create a single UNIX specification to ensure compatibility across platforms
-918 members in total
What are the fully certified varieties of UNIX?
Hewlett Packars: HP-UX
IBM: AIX
Apple: MacOS X
What are the mostly compliant varieties of UNIX?
most Linux distributions
Android
Cygwin(TF?)
What are the three layers UNIX is made up of?
The kernel
The shell
The program / application layer
What is telnet and some properties about it?
A virtual terminal connection
-application layer protocol over internet or local area network
-interactive text oriented communication
-unencrypted
What is ssh
It’s an encrypted version of telnet
What are the standard 3 unix editors and some of their properties
vi - specified in POSIX standard; lightweight
ed - line editor; very lightweight
emacs - incredibly flexible (and complicated); heavyweight