Restructuring Strings

Recall that a "string" in C is just a char *, the address of the first byte in a sequence of bytes, the last of which is \0 by convention. For instance, Zamyla and Andi might be stored in memory per the below.

---------------------------------------------------
| 'Z' | 'a' | 'm' | 'y'  | 'l' | 'a' | '\0' | 'A' |
---------------------------------------------------
| 'n' | 'd' | 'i' | '\0' |     |     |      |     |
---------------------------------------------------
|     |     |     |      |     |     |      |     |
---------------------------------------------------
|     |     |     |      |     |     |      |     |
---------------------------------------------------

Suppose that a string were instead represented without a trailing \0 character, with the string’s length instead stored in its first byte. For instance, Zamyla and Andi might instead be stored in memory per the below.

--------------------------------------------------
|  6  | 'Z' | 'a' | 'm' | 'y'  | 'l' | 'a' |  4  |
-------------------------------------------------
| 'A' | 'n' | 'd' | 'i' |      |     |     |     |
--------------------------------------------------
|     |     |     |     |      |     |      |    |
--------------------------------------------------
|     |     |     |     |      |     |      |    |
--------------------------------------------------

According to this alternative representation, were s a char *, then the length of s would be s[0], and the first character of s would be s[1].

Answer the below in strings.txt.

Questions

  1. (2 points.) What’s an advantage of this alternative representation of strings?

  2. (2 points.) What’s a disadvantage of this alternative representation of strings?

  3. (2 points.) Complete the reimplementation of strlen, below, in such a way that it returns the length of a string that’s implemented per this alternative representation.

    #include <string.h>
    
    size_t strlen(const char *s)
    {

    You can test your implementation with inputs like the below, each of which is just an array of characters (statically declared) that represents such a string.

    char zamyla[] = {6, 'Z', 'a', 'm', 'y', 'l', 'a'};
    char andi[] = {4, 'A', 'n', 'd', 'i'};

Debrief

  1. Which resources, if any, did you find helpful in answering this problem’s questions?

  2. About how long did you spend on this problem’s questions?