Link back to syllabus

You may find the strings library reference helpful. To use these functions, #include <string.h>.

  1. Safe reading

    Write a program that reads in a line of user input (up to 20 characters) safely. By safe here, I mean that your program should not access memory outside of the bounds of its arrays even when the user types in too much.

    Use getchar to do the reading, not the %ns feature of scanf.

    Turn your program into a function void safe_gets(char* s, int n). The parameter s points to a region of memory to fill and n is the number of characters in that region. (Remember that you can read one fewer character than you have space for, because of '\0'.)

  2. Palindromes

    Write a bool is_palindrome(char* s) function to detect whether or not a string is a palindrome, in two different ways:

    1. Use a loop that works from the end and from the beginning to see if the characters are the same.

    2. Make a reversed copy of the string and then use strcmp to compare the original to the reversed version.

  3. Searching

    Write a function int find_str(char* sub, char* str) that looks for an occurrence of the string sub in the string str. It returns the index of the start of sub within str if sub is found, or -1 otherwise. For example, find_str("ell", "Why, hello there!") returns 6, and find_str("ell", "Good-bye.") returns -1.

    Use the library function strstr.