Arrays and Strings in C

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

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.

False (B)

What is the term for accessing a single element from an array?

indexing

In C, the first element in an array is at index __.

<p>0</p> Signup and view all the answers

Match the array element with its corresponding value based on the given array: int arr[5] = {10, 20, 30, 40, 50};

<p>arr[0] = 10 arr[2] = 30 arr[4] = 50 arr[1] = 20</p> Signup and view all the answers

What does a for loop variable act as when iterating over an array?

<p>The index (A)</p> Signup and view all the answers

In C, the length of an array is automatically included as a part of the array itself.

<p>False (B)</p> Signup and view all the answers

When passing an array to a function, what does the value/name of the array give you?

<p>address</p> Signup and view all the answers

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.

<p>alias</p> Signup and view all the answers

Match the steps for passing an array as parameter:

<p>Using the array name as argument = Passes the array to the function The declared parameter in a function = Acts as an alias of the array To find size of the array = Pass it as another parameter</p> Signup and view all the answers

What is the implication of doing the following? int j = a[3];

<p><code>j</code> is assigned the value stored at <code>a[3]</code>. (B)</p> Signup and view all the answers

It is possible to assign a new value to an entire array in C after its initialization.

<p>False (B)</p> Signup and view all the answers

If you declare an array without initializing all its elements, what value are the remaining elements initialized to?

<p>zero</p> Signup and view all the answers

In C, the value of an uninitialized array depends on the __________ of the array.

<p>scope</p> Signup and view all the answers

Match the array scope to the initialization:

<p>Uninitialized global array = Zero-filled Uninitialized local array = Filled with garbage values</p> Signup and view all the answers

What is the correct way to define the length of an array in a C program? (as recommended by the text)

<p>Using a preprocessor macro. (C)</p> Signup and view all the answers

Using Variable Length Arrays (VLAs) is the preferred method for creating arrays in C, especially when the size is determined at runtime.

<p>False (B)</p> Signup and view all the answers

In the C memory model, how are array elements arranged?

<p>contiguously</p> Signup and view all the answers

Adding an integer i to a pointer moves the pointer over by i __________ in the array.

<p>elements</p> Signup and view all the answers

Associate the element with it's memory address considering the value of i to be 2:

<p><code>p + i</code> = Memory address <code>i</code> cells after memory address <code>p</code> <code>*(p + i)</code> = Value present in memory address <code>i</code> cells after memory address <code>p</code></p> Signup and view all the answers

According to the C standard, when is pointer arithmetic considered valid?

<p>Only within an array. (B)</p> Signup and view all the answers

In C, there is no practical difference between an array identifier and an immutable pointer.

<p>True (A)</p> Signup and view all the answers

What happens to the address of an array when it is passed to a function?

<p>copied</p> Signup and view all the answers

The sizeof operator returns the number of __________ values required to store a type or variable.

<p>char</p> Signup and view all the answers

Match variable type to the sizeof operator's return size (in bytes):

<p><code>char</code> = 1 <code>int</code> = 4 <code>short int</code> = 2 <code>long long int</code> = 8</p> Signup and view all the answers

What does the size of an int depend on?

<p>The operating system or processor architecture. (A)</p> Signup and view all the answers

Using sizeof is always the best way to determine the length of an array in C.

<p>False (B)</p> Signup and view all the answers

What is the term used to describe the integer "distance" between two pointers that point to elements within the same array?

<p>subtraction</p> Signup and view all the answers

Multi-dimensional arrays are represented by mapping the higher dimensions down to one dimension by __________ the array.

<p>flattening</p> Signup and view all the answers

Relate the string with the null character terminator expression:

<p><code>'\0'</code> = Equivalent to 0 <code>'0'</code> = Equivalent to 48 (ASCII character for symbol zero)</p> Signup and view all the answers

What is the significance of the null character in C strings?

<p>It marks the end of a string. (B)</p> Signup and view all the answers

The character arrays {'c', 'a', 't'} and "cat" are equivalent ways to define a string in C.

<p>False (B)</p> Signup and view all the answers

In C, what is the term for the number of characters in a string before the null terminator?

<p>length</p> Signup and view all the answers

The printf placeholder for strings is __________.

<p>%s</p> Signup and view all the answers

Given char a[] = "example"; What will following print? printf("%s", a);

<p>Output = <code>example</code></p> Signup and view all the answers

What is the maximum field width in scanf used for?

<p>To prevent reading more characters than the buffer can hold. (C)</p> Signup and view all the answers

It is generally safe to use scanf with the %s specifier without a maximum field width.

<p>False (B)</p> Signup and view all the answers

What is the term for comparing strings character by character until a difference is found or one of the strings ends?

<p>lexicographical order</p> Signup and view all the answers

The function used to compare two strings in C is __________.

<p>strcmp</p> Signup and view all the answers

Associate which value strcmp returns given the following: strcmp(str1, str2)

<p>zero = both string are equal positive integer = <code>str1</code> comes after <code>str2</code> negative integer = <code>str1</code> comes before <code>str2</code></p> Signup and view all the answers

When comparing strings for equality, what should you NOT use? (and why)

<p>Relational operators (==, &lt;, &lt;=, etc.) (they compare addresses) (C)</p> Signup and view all the answers

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.

<p>True (A)</p> Signup and view all the answers

What is created in the read-only data section for each string literal in C?

<p>null-terminated const char array</p> Signup and view all the answers

Flashcards

What is an array?

A contiguous block of memory holding elements of the same data type.

How to define arrays

Specify the type, name, and length in square brackets.

Array type

Each item in the array must be of the same data type.

What is indexing?

Accessing an array element using its index (position).

Signup and view all the flashcards

Array index

The position of an element in the array; starts from zero.

Signup and view all the flashcards

What is array iteration?

Looping through an array, processing each element.

Signup and view all the flashcards

Array address

The value/name of an array gives you the address of the array

Signup and view all the flashcards

Array name as pointer

The name of the array acts as a pointer to the first element.

Signup and view all the flashcards

What is out-of-bounds access?

Reading or writing to specific locations in memory without proper bounds checking.

Signup and view all the flashcards

What is a flattened array?

Multi-dimensional arrays must flatten to be used effectively.

Signup and view all the flashcards

What is a C-string?

An array of characters terminated by a null character ('\0').

Signup and view all the flashcards

What is a null terminator?

The '\0' character that marks the end of a C-string.

Signup and view all the flashcards

What is string length?

The number of characters before the null terminator.

Signup and view all the flashcards

How to print strings in C?

Use %s as the placeholder instead

Signup and view all the flashcards

Safe string creation

Be sure there is always a null terminator.

Signup and view all the flashcards

Maximum field width

It is a maximum limit of an input field.

Signup and view all the flashcards

Buffer overflow

Reading more characters than buffer size allows.

Signup and view all the flashcards

Safer buffer use

Always use a maximum field width 1 less than buffer length.

Signup and view all the flashcards

Never use gets

Never ever use scanf("%s", buf).

Signup and view all the flashcards

Lexicographical order

Comparing characters until a difference or end ('\0') is reached.

Signup and view all the flashcards

How to safely compare strings

strcmp checks for zero result.

Signup and view all the flashcards

String result

strcmp(a,b) = '0' there is no difference

Signup and view all the flashcards

strcpy(dest, src) overwrites dest

Overwrites contents with src copies to the end.

Signup and view all the flashcards

strcat(dest, src) to end

Copies to the end concatenates.

Signup and view all the flashcards

Copy avoid overlap

The string version of strcat

Signup and view all the flashcards

Memory diagram

It is a pointer to the data.

Signup and view all the flashcards

arrays of chars

This value is stored stack func.

Signup and view all the flashcards

Read Data string

NullTerm, create in read data

Signup and view all the flashcards

Constant and Point

More similar constant, in code express a

Signup and view all the flashcards

Char point text

Char * pointer?

Signup and view all the flashcards

Array string

A defining array in string

Signup and view all the flashcards

Work array string

Array is not string, you must length 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 with printf(" %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 moves i elements over from the array
  • If we add i to the pointer that moves it over by i elements, while the pointer shifts by 4
  • Size of int on architecture

Array Pointer Notation

  • a[i] is shorthand for *(&a[0] + i)

  • array_function(int a[], int len) is equivalent to array_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 to char * inside the array, it moves i elements over

  • Adding i still moves element over by i elements

  • However, the pointer is changed by 4 because of the int 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 as 48

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 the printf 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 string a 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 be 1 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 from src to dest
  • Use pointer arithmetic, and ensure there are only type char * variables
  • strcat(char *dest, const char *src) concatenates src contents to the dest 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"
  • 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 and a would be equivalent, but the differences show different values for value, there is an &a while it also appears for &p and p sizeof(a) produces 24 instead when sizeof(p) results in 8

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
  1. 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.";
  2. A character array: char *chap [4] = {"'Twas brillig, and the slithy toves",...}
  3. 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.

Quiz Team

Related Documents

More Like This

Array Indexing
10 questions

Array Indexing

GreatestFreesia avatar
GreatestFreesia
Array Indexing Basics
18 questions
NumPy Array Indexing and Slicing
6 questions
Use Quizgecko on...
Browser
Browser