Lab: Strings, continued

This laboratory examines details of string storage, and the operations of string library functions within the C programming language.

A. Arguments to main

Arguments to main provide a useful opportunity to give parameters to programs, which are used to direct the way the program goes about its task.

The declaration of main looks like this:

int main(int argc, char *argv[]);

There are at least two arguments to main: argc and argv. The first of these is a count of the arguments supplied to the program and the second is an array of pointers to the strings which are those arguments. These arguments are passed to the program by the host system’s command line interpreter.

The following declaration is equivalent to that shown above:

int main(int argc, char **argv);

Exercises

  1. Read through the following block of code.
    int main(int argc, char *argv[])
    {
     for (int i = 0; i < argc; i++) {
         printf("arg %d: %s\n", i, *argv++);
     }
    }
    

    Write down your predictions for what the printf statements would print if you type in the console:

    1.  ./args + 4.0 4.5 	
      
    2.  ./args sum text 2
      
    3.  ./args encrypt "This message"
      

      Compile and run this code to check your predictions. If your predictions are incorrect, discuss your answers with your instructor or mentor.

  2. The library offer a set of string-conversion functions such as `atoi`, `strtod`, among others.
    • Go to your terminal and type man atoi. What is the purpose of atoi?
    • Go to your terminal and type man strtod. What is the purpose of strtod?
  3. Write a program countSubstring.c that counts and displays the number of substrings that match a target string. Consider running your program with the following command-line input
    ./countSubstring "this and this and that and this" this
    

    The output of the program should be

    the substring "this" appears 3 times.