Given the following variable declarations, which of the following lines are syntactically valid ways that character and string types can interact?
char c, s[20];
c = s[0];
s = c;
c = "A";
s = 'A';
c = 'A';
s[0] = c;
Hint1.
There is no string type; instead, strings are implemented as arrays of chars. You can’t simply interchange strings and chars in a line of code, as they are fundamentally different under the hood.
Hint2.
Character literals use single quotes, like: ’A’. String literals use double quotes, like: "A".
Exercise2.6.2.The strlen Function.
What will strlen("Hello!") return?
Hint.
The null character at the end of a string takes up a byte of memory, but it does not count for the string length.
Exercise2.6.3.Storing Strings.
Suppose you want to store this string: "Hello!" How many bytes do you have to pass to malloc to allocate enough memory to store it?
Hint1.
Each character takes up one byte of memory.
Hint2.
Don’t forget the null character at the end of the string takes up one byte of memory!
Exercise2.6.4.Storing Strings and strcat.
Suppose you have the strings "Hello" and "World" and you strcat them together. How many bytes are needed to store the result?
Hint.
Recall that strcat concatenates two strings together.
Exercise2.6.5.Code Safety.
Which of these functions is a safer alternative to strcpy?
strncpy
Correct
strtok
Incorrect
ststr
Incorrect
sprintf
Incorrect
Hint.
There is a version of strcpy that adds safety by passing in an N value that is the maximum size to copy, which is usually the size of the destination string.
Exercise2.6.6.Dynamic String Concatenation.
Put these lines of code in order to successfully create the string "Hello World" (held in result) after the code finishes.
char str1[10], str2[10], *result;
int len;
---
strcpy(str1, "Hello ");
strcpy(str2, "World");
---
len = strlen(str1) + strlen(str2) + 1;
---
result = (char*)malloc(len);
---
strcpy(result, str1);
---
strcat(result, str2);
---
printf("%s\n", result);
---
len = sizeof(str1) + sizeof(str2) + 1; #distractor
---
len = sizeof(str1) + sizeof(str2); #distractor
---
len = strlen(str1) + strlen(str2); #distractor
Hint.
Think about whether you should do a string copy or a string concatenation first.
Exercise2.6.7.String Overflow and Undefined Behavior.
Identify (by clicking) all of the lines that would result in string overflow or undefined behavior in the program below:
There are instances when strcat can be used safely. While strncat is a safer alternative to strcat, you should not become complacent. You can still easily buffer overflow if there’s not enough room in the destination string to copy the characters into.