Podcast
Questions and Answers
When defining an array, what follows the type
of each item in the array?
When defining an array, what follows the type
of each item in the array?
- Semicolon
- Initialization values in curly braces
- Name of the variable (correct)
- Length of the array in parentheses
Once the length of an array is created, it can be changed.
Once the length of an array is created, it can be changed.
False (B)
What is the term for accessing a single element from an array?
What is the term for accessing a single element from an array?
indexing
In C, the first element in an array is at index __.
In C, the first element in an array is at index __.
Match the array element with its corresponding value based on the given array:
int arr[5] = {10, 20, 30, 40, 50};
Match the array element with its corresponding value based on the given array:
int arr[5] = {10, 20, 30, 40, 50};
What does a for
loop variable act as when iterating over an array?
What does a for
loop variable act as when iterating over an array?
In C, the length of an array is automatically included as a part of the array itself.
In C, the length of an array is automatically included as a part of the array itself.
When passing an array to a function, what does the value/name of the array give you?
When passing an array to a function, what does the value/name of the array give you?
When an array is passed as a parameter to a function, the parameter in the called function becomes an __________ of the array in the caller.
When an array is passed as a parameter to a function, the parameter in the called function becomes an __________ of the array in the caller.
Match the steps for passing an array as parameter:
Match the steps for passing an array as parameter:
What is the implication of doing the following?
int j = a[3];
What is the implication of doing the following?
int j = a[3];
It is possible to assign a new value to an entire array in C after its initialization.
It is possible to assign a new value to an entire array in C after its initialization.
If you declare an array without initializing all its elements, what value are the remaining elements initialized to?
If you declare an array without initializing all its elements, what value are the remaining elements initialized to?
In C, the value of an uninitialized array depends on the __________ of the array.
In C, the value of an uninitialized array depends on the __________ of the array.
Match the array scope to the initialization:
Match the array scope to the initialization:
What is the correct way to define the length of an array in a C program? (as recommended by the text)
What is the correct way to define the length of an array in a C program? (as recommended by the text)
Using Variable Length Arrays (VLAs) is the preferred method for creating arrays in C, especially when the size is determined at runtime.
Using Variable Length Arrays (VLAs) is the preferred method for creating arrays in C, especially when the size is determined at runtime.
In the C memory model, how are array elements arranged?
In the C memory model, how are array elements arranged?
Adding an integer i
to a pointer moves the pointer over by i
__________ in the array.
Adding an integer i
to a pointer moves the pointer over by i
__________ in the array.
Associate the element with it's memory address considering the value of i
to be 2
:
Associate the element with it's memory address considering the value of i
to be 2
:
According to the C standard, when is pointer arithmetic considered valid?
According to the C standard, when is pointer arithmetic considered valid?
In C, there is no practical difference between an array identifier and an immutable pointer.
In C, there is no practical difference between an array identifier and an immutable pointer.
What happens to the address of an array when it is passed to a function?
What happens to the address of an array when it is passed to a function?
The sizeof
operator returns the number of __________ values required to store a type or variable.
The sizeof
operator returns the number of __________ values required to store a type or variable.
Match variable type to the sizeof
operator's return size (in bytes):
Match variable type to the sizeof
operator's return size (in bytes):
What does the size of an int
depend on?
What does the size of an int
depend on?
Using sizeof
is always the best way to determine the length of an array in C.
Using sizeof
is always the best way to determine the length of an array in C.
What is the term used to describe the integer "distance" between two pointers that point to elements within the same array?
What is the term used to describe the integer "distance" between two pointers that point to elements within the same array?
Multi-dimensional arrays are represented by mapping the higher dimensions down to one dimension by __________ the array.
Multi-dimensional arrays are represented by mapping the higher dimensions down to one dimension by __________ the array.
Relate the string with the null character terminator expression:
Relate the string with the null character terminator expression:
What is the significance of the null character in C strings?
What is the significance of the null character in C strings?
The character arrays {'c', 'a', 't'} and "cat" are equivalent ways to define a string in C.
The character arrays {'c', 'a', 't'} and "cat" are equivalent ways to define a string in C.
In C, what is the term for the number of characters in a string before the null terminator?
In C, what is the term for the number of characters in a string before the null terminator?
The printf
placeholder for strings is __________.
The printf
placeholder for strings is __________.
Given
char a[] = "example";
What will following print?
printf("%s", a);
Given
char a[] = "example";
What will following print?
printf("%s", a);
What is the maximum field width in scanf
used for?
What is the maximum field width in scanf
used for?
It is generally safe to use scanf
with the %s
specifier without a maximum field width.
It is generally safe to use scanf
with the %s
specifier without a maximum field width.
What is the term for comparing strings character by character until a difference is found or one of the strings ends?
What is the term for comparing strings character by character until a difference is found or one of the strings ends?
The function used to compare two strings in C is __________.
The function used to compare two strings in C is __________.
Associate which value strcmp
returns given the following:
strcmp(str1, str2)
Associate which value strcmp
returns given the following:
strcmp(str1, str2)
When comparing strings for equality, what should you NOT use? (and why)
When comparing strings for equality, what should you NOT use? (and why)
strcpy
overwrites the destination array with the contents of the source array, while strcat
appends the source array to the end of the destination array.
strcpy
overwrites the destination array with the contents of the source array, while strcat
appends the source array to the end of the destination array.
What is created in the read-only data section for each string literal in C?
What is created in the read-only data section for each string literal in C?
Flashcards
What is an array?
What is an array?
A contiguous block of memory holding elements of the same data type.
How to define arrays
How to define arrays
Specify the type, name, and length in square brackets.
Array type
Array type
Each item in the array must be of the same data type.
What is indexing?
What is indexing?
Signup and view all the flashcards
Array index
Array index
Signup and view all the flashcards
What is array iteration?
What is array iteration?
Signup and view all the flashcards
Array address
Array address
Signup and view all the flashcards
Array name as pointer
Array name as pointer
Signup and view all the flashcards
What is out-of-bounds access?
What is out-of-bounds access?
Signup and view all the flashcards
What is a flattened array?
What is a flattened array?
Signup and view all the flashcards
What is a C-string?
What is a C-string?
Signup and view all the flashcards
What is a null terminator?
What is a null terminator?
Signup and view all the flashcards
What is string length?
What is string length?
Signup and view all the flashcards
How to print strings in C?
How to print strings in C?
Signup and view all the flashcards
Safe string creation
Safe string creation
Signup and view all the flashcards
Maximum field width
Maximum field width
Signup and view all the flashcards
Buffer overflow
Buffer overflow
Signup and view all the flashcards
Safer buffer use
Safer buffer use
Signup and view all the flashcards
Never use gets
Never use gets
Signup and view all the flashcards
Lexicographical order
Lexicographical order
Signup and view all the flashcards
How to safely compare strings
How to safely compare strings
Signup and view all the flashcards
String result
String result
Signup and view all the flashcards
strcpy(dest, src) overwrites dest
strcpy(dest, src) overwrites dest
Signup and view all the flashcards
strcat(dest, src) to end
strcat(dest, src) to end
Signup and view all the flashcards
Copy avoid overlap
Copy avoid overlap
Signup and view all the flashcards
Memory diagram
Memory diagram
Signup and view all the flashcards
arrays of chars
arrays of chars
Signup and view all the flashcards
Read Data string
Read Data string
Signup and view all the flashcards
Constant and Point
Constant and Point
Signup and view all the flashcards
Char point text
Char point text
Signup and view all the flashcards
Array string
Array string
Signup and view all the flashcards
Work array string
Work array string
Signup and view all the flashcards
Study Notes
- The primary objective of this section involves using arrays and strings
Arrays
- To define an array variable, specify the type of items, variable name, and length in square brackets
- Arrays can be initialized with an equals sign and values enclosed in curly braces like this:
int a = {1, 1, 2, 5, 14, 42}
- The length of an array is fixed once created
- Each item in an array must be of the same type
- Arrays can perform some of the functions that lists do in Racket
- Elements can be extracted from an array through indexing, using square brackets and an integer index after the array's name
Array Indexing
- In C, the first element of an array is at index 0 and not 1
- The index of the element is always one less than its length
- The index of an element indicates number of elements before it
Iterating through Arrays
for
loops can iterate over arrays using the loop variable as the index- In C, the array length is separate and must be tracked independently
int jvj = {2,4,6,0,1}
declares and initializes an integer array named 'jvj'const int len = 5
declares a constant integer 'len' and assigns it the value 5, likely representing the length of the array- This
for
loop withprintf(" %d", jvj[i])
iterates through 'jvj' and prints each element printf("\n")
adds a newline character after printing the array elements
Arrays as Parameters
- The value/name of an array gives the array address
- Arrays can be passed as function arguments by using the array name
- In the
print_array
function,arr[]
is an alias for the array passed in the caller - A separate parameter for the array length is needed since arrays do not store their length
Reading and Writing Array Elements
- Individual array elements can be read from and written to like regular variables
a[2] = a[a[3]]
an example of writing to array elements- The value of an uninitialized array is dependent upon its scope
Array Initialization
- Arrays can be initialized using curly braces, such as
int a = {1, 1, 2, 5, 14, 42}
- Remaining elements are initialized to zero if not enough values are provided in the initializer list
- Assigning a new value to an entire array is not permitted, but individual elements can be mutated
a = {1, 2, 3, 4, 5, 6}
is an invalid operation
Uninitialized Arrays
- Skipping array initialization can save time, but can lead to working with garbage data
- Always initialize your arrays
- The value of an uninitialized array depends on its scope
- Global arrays are prefilled with zeros, whereas local arrays contain junk data from the stack
Array Length
- The array length is never part of the array data structure in C
- The array length must always be kept track of separately
- You improve readability by storing the length in a separate variable
Array Length (Continued)
- It's considered incorrect C style to specify the array length using a constant
- It's considered okay to use magic numbers when defining arrays
- A macro specifies the length of an array
- Assigning A_LEN the integer value of 6
#define A_LEN 6
- You aren't allowed to use variable length arrays in this course
Size of Operator
-
The
sizeof
operator outputs the number of char values that require storage for either a variable or type -
It’s an operator, though
sizeof
may look like it functions as a function -
sizeof(char)
is by definition 1 -
The architecture determines the size of an int
-
Items will always be separated within an array by the
sizeof
only a single item -
The size of an
int
relies on a specific machine (processor) and/or the operating system on which it is currently running -
The
inttypes
module in C99 outlines a variety of types that define the exact number of bytes to use -
Only integers should be used with there always being 32 bits
-
A pointer is always the same size
-
It is not recommended to use
sizeof
on an array -
But the compiler is able to determine exactly how big it is in the scope where the array is defined
-
Elsewhere all that is available is a pointer
Pointer Arithmetic
- If an integer
i
is added to a pointer, this pointer movesi
elements over from the array - If we add
i
to the pointer that moves it over byi
elements, while the pointer shifts by4
- Size of
int
on architecture
Array Pointer Notation
-
a[i
] is shorthand for*(&a[0] + i)
-
array_function(int a[], int len)
is equivalent toarray_function(int *a, int len)
-
An immutable pointer doesn't differ much from an array identifier
-
The value of an array which is
a
is the same thing as the array address -
Functions must require valid length
-
Arrays don't store their own length
-
If
i
is added tochar *
inside the array, it movesi
elements over -
Adding
i
still moves element over byi
elements -
However, the pointer is changed by
4
because of theint
size on the current architecture
Multi-Dimensional Data
- One-dimensional arrays have been the arrays visible up to now
- The C language has support for data that is multi-dimensional
- There are limitations to arrays that are multi-dimensional inside of C
- A typical method is representing data that is multi-dimensional by "mapping" the dimensions that are higher down to only a single dimension through flattening the array
- The data must always be stored separately including the length of the array must be at a minimum always be as long as their product
Arrays of Strings
- Since there is no built-in C string type, a string in C is represented as an array of characters terminated by a null character
- For example,
char my_string = {'c', 'a', 't', '\0'}
- The char with the value of zero goes by the moniker null terminator is often written as
'\0'
'\0'
is the same as 0- However, this is unlike
'0'
which is the same as48
String Initialization
- The following produce identical 4-character arrays:
char a = {'c', 'a', 't', '\0'}
char b = {'c', 'a', 't', 0}
char c = {'c', 'a', 't'}
char d = {99, 97, 116, 0}
char e = "cat"
char f = "cat\0"
char g[] = "cat"
- They are strings because they have null terminators
Null Termination
- Null terminated strings don't require the length to pass functions
- A string's length is the number or characters prior to the first
'\0'
- There is a function called
strlen
in the string library, that performs the same - It is better to use a library function
String I/O
-
The format specifier
%s
can be used with theprintf
function to print strings to standard output -
In this case,
char a[] = "cat"
creates a string with the value "cat" -
This
printf("the %s in the hat\n", a)
uses the variable stringa
to print output -
This prints any characters prior to the null character
-
It reads characters one "word" at a time prior to read n chars, stopping anytime it has white space
-
n
is the width of the maximum field. -
It will add a null operator making
n
must be1
smaller than that buffer -
There exists code that uses
%s
without a maximum width -
It is attempted to introduce bugs
Lexicographical Order
- A
char
value has a well-defined order which dictates if corresponding values follow the order in order - The value of comparing the two
char *
looks only at the values - Rarely useful
- If the comparison of a string to its typical interesting part involves utilizing lexicographical order. The comparison character by character must go until either a string becomes empty or the two strings begin to differ
'b'
appears prior to the 'n
', indicating"Frobisher"
appears prior to"Frontenac"
strcmp(a, b) == 0
with is no difference- The relational operators should never be utilized which include
==
to<
to<=
in order to begin comparison process of strings. The strings contents are never compared, only their addresses
Copying Strings
strcpy(char *dest, const char *src)
overwrites the contents fromsrc
todest
- Use pointer arithmetic, and ensure there are only type
char *
variables strcat(char *dest, const char *src)
concatenatessrc
contents to thedest
string end- Whenever the usage of this takes hold, the must be properly spacing which includes for the null terminator
String Literals
- String literals are enclosed in quotations
- They come in two types:
- To initialize characters of an array:
char a[] = "this is not a literal; it merely initializes an array in the stack"
which is stored in a stack frame. - In expressions: e.g.,
char *ptr = "this is a literal; the stack stores a pointer to it"
- To initialize characters of an array:
- String literals are created in a read-only data section, no name
- For their occurrence in any code, a replacement takes place with an corresponding array address
- In many of the practical expressions, the values of
p
anda
would be equivalent, but the differences show different values for value, there is an&a
while it also appears for&p
and psizeof(a)
produces24
instead whensizeof(p)
results in8
Arrays of Strings
- These require dynamic memory which is defining the array of mutable strings with the intent of being a bit more awkward
- They must be defined with the intention of being a separate mutable string. Asides from its mutability, the
char*
will be practically same as the previous - Internally, there must be equivalent values.
char*j0 = "Twas brillig, and the slithy toves";
, it does this by there being string literals and cap has to have pointers - If it's done through this method, there won't be any mutation of any individual literals
- There exist three types include
- a string through
char cha[134] = "'Twas brillig, and the slithy toves\nDid gyre and gimble in the wabe;\nAll mimsy were the borogoves,\nAnd the mome raths outgrabe.";
- A character array:
char *chap [4] = {"'Twas brillig, and the slithy toves",...}
- An array with
chat chart [4][36] = {"'Twas brillig, and the slithy toves"\n Did gyre and gimble in the wabe"}
- Anytime the work is taking place with a non-string array, the length
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.