0
 string book[] = {
        "Chen",
        "Kernighan",
        "Leitner",
        "Lewis",
        "Malan",
        "Muller",
        "Seltzer",
        "Shieber",
        "Smith"
    }

    int main(void)
        {
            // Prompt user for name
            string name = get_string("Name: ");

            // Search for name
            if (search(name, book, 0, sizeof(book) / sizeof(string) - 1))
            {
                printf("Calling %s\n", name);
            }
            else
            {
                printf("Quitting\n");
            }
        }

After completing problem set 3, I decided that it wouldn't be too bad of an idea to take a look at the implementations of sorts in the source code of the lecture. While looking at the binary sort, I saw that the right bound of the search was defined as above as sizeof(book) / sizeof(string) - 1. I dedcided to put each as a variable and ran them through debug50 to see their value. It showed that the size of the string was 8, where as the size of the book is 72. How were these values calculated, and furthermore how is it able to describe the right bound of the search?

1

That code calculates the number of elements in the array book[]. sizeof(book) is the total size of the array, 72 bytes. Next, remembering that this is an array of pointers to strings ( the CS50.h string type is equivalent to a char array and the starting point of that string is an address), sizeof(string) is the size of a pointer, or 8 bytes. Divide 72 by 8 and you get 9 elements in the array.

Now, without seeing the search() function (I haven't looked at it in a long time), I'm assuning that the last parameter is the number of the last array element, not the number of elements (due to starting at 0). So now, let's look at the whole parameter:

sizeof(book) / sizeof(string) - 1

Because of the order of operations, it's actually this:

(sizeof(book) / sizeof(string)) - 1 
(   72   /   8  ) - 1
(   9   ) - 1
= 8

So, the last element is book[8].

Does that make sense to you?

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • Disreguard this edit, I understand now.
    – Davis
    Jun 29 '18 at 1:01
  • No, the numbers won't change. The pointers in the array point to the strings. It doesn't matter what's in the strings. Think of it this way. My hand points at a house on monday, and an apartment complex on tuesday. No matter which building it points at, or how many people (they're real characters! :-P) live there, my hand, the pointer, is always the same size. ;-)
    – Cliff B
    Jun 29 '18 at 1:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .