COP 3514 Exam 2

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

To find the address of a variable, we use the

& (address) operator

Operations that cause undefined behavior Performing arithmetic on a pointer that doesn't point to an array element (1) Subtracting pointers but they do not point to elements of the same array (2)

(1) int i, *p, *q; p = &i; q = p+3; //wrong (2) int a[10], b[20]; p = &a[0]; q =&b[10]; int i = q - p; //wrong

To gain access to the object that a pointer points to, we use the

* (indirection) operator

What are the values of x and y after calling swap(&x, &y) with the swap function defined as follows? Assume int x = 3, y = 4; void swap (int a, int b) { int temp = a; a = b; b = temp; } A) 3 4 B) 4 3 C) 3 3 D) 4 4

A

Which one of the statements will print the elements of an array in reverse order? A) for (p = a + N - 1; p >= a; p--) printf("%d ", *p); B) for (p = a + N; p >= a; p--) printf("%d ", *p); C) for (p = a + N -1; p > a; p--) printf("%d ", *p); D) for (p = a + N; p > a; p--) printf("%d ", *p);

A

int a[]={6, 19, 35, 74, 23, 16}; int *p = &a[1]; int *q = &a[5]; What's the value of q - p? A)4 B)-4 C)3 D)-3 E)None of the above

A

String Library Functions

Compare strings - strcmp • Length of a string - strlen • Copy strings - strcpy - strcat • Search and tokenize strings - strstr - strtok

Exercise What will be the value of string s1 after the following statements have been executed? strcpy(s1, "String"); strcpy(s2, "Library"); if (strcmp(s1, s2) < 0) strcat (s1, s2); else strcat(s2, s1); A) String B) Library C) StringLibrary D) LibraryString E) None of the above

D

int a[]={6, 19, 35, 74, 23, 16}; int *p = &a[1]; int *q = &a[5]; What's the value of *(q-3)? A)74 B)13 C)19 D)35 E)None of the above

D

int a[]={6, 19, 35, 74, 23, 16}; int *p = &a[1]; int *q = &a[5]; What's the value of *q - *p? A)4 B)-4 C)3 D)-3 E)None of the above

D

C supports three (and only three) forms of pointer arithmetic (True or False): - Adding an integer to a pointer - Subtracting an integer from a pointer - Subtracting one pointer from another

True

Functions are allowed to return pointers (True or False)

True

Pointers can be compared using the relational operators (<, <=, >, >=) and the equality operators (== and !=). - Using relational operators is meaningful only for pointers to elements of the same array. (True or False)

True

Pointers can point to array elements. (True or False)

True

Pointers passed as arguments in a function allow variables to be updated (True or False)

True

The condition p < &a[N] in the for statement (True or False): - It's legal to apply the address operator to a[N], even though this element doesn't exist. - It's safe since the loop doesn't attempt to examine its value. - Loop terminates when p is equal to &a[N].

True

The name of an array can be used as a pointer to the first element in the array (true or false)

True

for (p = &a[0]; p < &a[N]; p++) sum += *p; is equivalent to (True or False) p = &a[0]; while (p < &a[N]) sum += *p++;

True

p* = 1 (True or False)

True

segmentation fault

fault occurs when you try to access memory that you have no right to access

What is q pointing to in this code? int i; int *p; int *q; p = &i; q = p;

i

Command-Line Arguments (true or false) To obtain access to command-line arguments, main must have two parameters: int main(int argc, char *argv[]) argc ("argument count") is the number of command-line arguments. • argv ("argument vector") is an array of pointers to the command-line arguments (stored as strings). • argv[0] points to the name of the program, while argv[1] through argv[argc-1] point to the remaining command-line arguments.

true

Copying a string into a character array using the = operator is not possible: char str1[10]= "abc"; char str2[10]= "def"; str2 = str1; /*** WRONG ***/ Using an array name as the left operand of = is illegal (true or false)

true

If the initializer is too short to fill the string variable, the compiler adds extra null characters: char date2[9] = "June 14"; (true or false)

true

Multidimensional Arrays (true or false) To access the element of m in row i, column j, we must write m[i][j]. - The expression m[i] designates row i of m, and m[i][j] then selects element j in this row.

true

Operations on String Literals A string literal (constant) should not be modified. Attempting to modify a string literal causes undefined behavior: char *p = "abc"; *p = 'd'; /*** WRONG ***/• A program that tries to change a string literal may crash or behave erratically. (true or false)

true

String Variables Any one-dimensional array of characters can be used to store a string. A string variable can be initialized at the same time it's declared: char date1[8] = "June 14"; The compiler will automatically add a null character so that date1 can be used as a string: "June 14" is not a string literal in this context. (true or false)

true

String Variables• If a string variable needs to hold 80 characters, it must be declared to have length 81: #define STR_LEN 80 ... char str[STR_LEN+1]; Adding 1 to the desired length allows room for the null character at the end of the string. Defining a macro that represents 80 and then adding 1 separately is a common practice. (true or false)

true

Strings are treated as arrays in C, so they're restricted in the same ways as arrays. • In particular, they can't be copied or compared using operators. Programs that need string operations should contain the following line: #include <string.h> (true or false)

true

The %s conversion specification allows printf to write a string: char str[] = "Are we having fun yet?"; printf("%s\n", str); printf writes the characters in a string one by one until it encounters a null character. (true or false)

true

The NULL pointer (a macro definition in stdio.h) - A pointer that points to nothing. - int *p = NULL; (true or false)

true

The declaration char date[] = "June 14"; declares date to be an array, • The similar-looking char *date = "June 14"; declares date to be a pointer. • In the array version, the characters stored in date can be modified. In the pointer version, date points to a string literal that shouldn't be modified. (true or false)

true

The declaration of a string variable may omit its length, in which case the compiler computes it: char date4[] = "June 14"; • The compiler sets aside eight characters for date4, enough to store the characters in "June 14" plus a null character. • Omitting the length of a string variable is especially useful if the initializer is long, since computing the length by hand is error-prone. (true or false)

true

The strcat (String Concatenation) Function (true or false) strcat appends the contents of the string s2 to the end of the string s1.• It returns s1 (a pointer to the resulting string). strcat examples: strcpy(str1, "abc"); strcpy(str2, "def"); strcat(str1, str2); /* str1 now contains "abcdef" */

true

The strcmp (String Comparison) Function (true or false) As it compares two strings, strcmp looks at the numerical codes for the characters in the strings. Important properties of ASCII: - A-Z, a-z, and 0-9 have consecutive codes. - All upper-case letters are less than all lower -case letters. - Digits are less than letters. - Spaces are less than all printing characters.

true

The strcmp (String Comparison) Function (true or false) compares the strings s1 and s2, returning a value less than, equal to, or greater than 0. • To test whether str1 and str2 contain the same characters: if(strcmp(str1, str2)==0)

true

The strcpy (String Copy) Function (true or false) strcpy copies the string pointed to by s2 into the array pointed to by s1. strcpy returns s1 (a pointer to the destination string). strcpy(str2, "abcd"); /* str2 now contains "abcd" */ strcpy(str1, str2); /* str1 now contains "abcd" */

true

The strlen (String Length) Function (true or false) strlen returns the length of a string s, not including the null character. • Examples: int len; len = strlen("abc"); /* len is now 3 */ len = strlen(""); /* len is now 0 */

true

Two types of strings: - String constants (or literals, as they're called in the C standard) - String variables Strings are not a type in C . Strings are arrays of characters in which a special character—the null character—marks the end. (true or false)

true

When a C compiler encounters a string literal of length n in a program, it sets aside n + 1 bytes of memory for the string. This memory will contain the characters in the string, plus one extra character—the null character—to mark the end of the string. It is represented as the escape sequence '\0' (true or false)

true

atoi function (true or false) function in <stdlib.h> to convert a string to integer form. For example, if a string variable s contains "8". Then atoi(s) returns 8.

true

strcmp considers s1 to be less than s2 if either one of the following conditions is satisfied: - The first i characters of s1 and s2 match, but the (i+1)st character of s1 is less than the (i+1)st character of s2. For example, s1: "back", s2: "bag" - All characters of s1 match s2, but s1 is shorter than s2. For example, s1: "be", s2: "bee" (true or false)

true

void store_zeros(int a[], int n); void store_zeros(int *a, int n); These two functions are equivalent. (true or false)

true

Increment p first; value of expression is *p after increment

*++p or *(++p)

Value of expression is *p before increment; increment p later

*p++ or *(p++)

int a[]={6, 19, 35, 74, 23, 15}; int *p = &a[1]; int *q = &a[5]; What is the value of the condition *p < *q? 1(true) 0(false)

0 false

int a[]={6, 19, 35, 74, 23, 15}; int *p = &a[1]; int *q = &a[5]; What is the value of the condition p < q? 1(true) 0(false)

0 false

What is q pointing to in this code? (number/variable) int i, j; int *p; int *q; p = &i; q = &j; i = 1; *q = *p;

1 / j

What are the values of x and y after calling swap(&x, &y) with the swap function defined as follows? Assume int x = 3, y = 4; void swap (int *a, int *b) { int temp = *a; *a = *b; *b = temp; } A) 3 4 B) 4 3 C) 3 3 D) 4 4

B

int a[]={6, 19, 35, 74, 23, 16}; int *p = &a[1]; int *q = &a[5]; What's the value of *(p+3)? A)74 B)23 C)24 D)16 E)None of the above

B

i is int and p and q are pointers to int. Which assignment is illegal? A) p = &i; B) p = *&q; C) p = i;

C

Review all code examples and projects since Week 5 to week 8

Reviewed

Review read_line the pointer version for how to skip white space before beginning to store input characters

Reviewed

How String Literals Are Stored

Since a string literal is stored as an array, the compiler treats it as a pointer of type char *.• We can use a string literal wherever C allows a char * pointer: char *p; p = "abc";

Why should you never return a pointer to a local variable? (automatic storage duration) int *f(void){ int i; ... return &i; }

The variable i won't exist after f returns.

An initializer for a string variable can't be longer than the variable, but it can be the same length (bad practice) Why is this bad practice?

There's no room for the null character Failing to leave room for the null character may cause unpredictable results when the program is executed.

Displaying Pointer Values

int *p; printf("%p", p);

Declaring a pointer variable

int *p; or int i, j, *p, *q;

Adding an Integer to a Pointer if p points to the array element a[i], then p + j points to a[i+j]

int a[10]; int *p, *q, i; p = &a[2]; q = p + 3; // q = &a[5] p += 6; // p = &[8]

Assigning pointer p to address of i

int i; int *p; i = 5; p = &i;

Subtracting One Pointer from Another If p points to a[i] and q points to a[j], then p - q is equal to i - j

p = &a[5]; q = &a[1]; i = p - q; /* i is 4 */ i = q - p; /* i is -4 */

Subtracting an Integer from a Pointer If p points to a[i], then p - j points to a[i-j]

p = &a[8]; q = p - 3; // q = &a[5] p -= 6; // p = &a[2]

Attempting to compare strings using a relational or equality operator is legal but won't produce the desired result: if (str1 == str2) ... /*** WRONG ***/• str1 and str2 are compared as pointers. • Since str1 and str2 have different addresses, the expression str1 == str2 must have the value 0. (true or false)

true

A string literal is a sequence of characters enclosed within double quotes: "When you come to a fork in the road, take it."• When a string literal is too long: - The backslash character (\) can be used to continue a string literal from one line to the next: printf("When you come to a fork in the road, take it. \--Yogi Berra"); - When two or more string literals are adjacent, the compiler will join them into a single string. printf("When you come to a fork in the road, take it. " "--Yogi Berra"); (true or false)

true

Arrays of Strings (true or false) To create an array of strings with initial values, use a two-dimensional array of characters, with one string per row: char planets[][8] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"}; The number of rows in the array can be omitted, but C requires that we specify the number of columns. it can be modified: planets[0][2] = 'k'; ** note defined columns of 0-7 but rows in this case is 0-7 since theres 8 strings

true

Arrays of Strings (true or false) We can also create array in C by whose elements are string literals (read only): char *planets[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"}; ** note no columns and rows, just a list from 0-7

true

Common Causes of Segmentation Fault

•Forgetting to use "&" on the arguments to scanf •Forgetting to use "&" on the arguments to function as pointers •Incorrect use of the "&" (address of) and "*" (indirection) operators •Failure to initialize a pointer before accessing it


Kaugnay na mga set ng pag-aaral

vocabulary workshop level d units 1-4

View Set

Java Programming - Chapter 7: Arrays

View Set

Chapter 12 Vectors and the Geometry of Space

View Set

Managing People & work - QUIZ 10

View Set

Cyber Offensive and Defensive Network Operations

View Set

ap euro famous documents and treaties

View Set

Chapter 39: Assessment and Management of Patients With Rheumatic Disorders

View Set

Hey p.18-19, Hey p.22-23, Hey p.26-27

View Set

Chapter 1 introduction to materials science and engineering

View Set

NUR 301 | Chapter #14: Nursing Management-Patients With Coronary Vascular Disorders

View Set