6.4. Strings

  • A string is an array of char ending with \0.
  • When using printf() and scanf(), use the %s format statement for strings.

6.4.1. Initializing a string

  • char s[50]; Allocates memory for a string, but no assignment is made.
  • char s[] = "abc"; Allocates just enough memory for the string. In this case 4 char values (one for the null terminator \0).
  • char *p = "abc"; Only the pointer is in the stack. The pointer is set to memory in the text area of the program which holds the string “abc”, which is a constant.

6.4.2. String Example

Here is one possible way to implement a strlen function that returns the length of the string. The function uses a pointer that is incremented through the string.

int mystrlen( const char *st )
{
   char *ptr;
   int count = 0;

   for( ptr = st; *ptr != '\0'; ptr++ ) count++;
   return count;
}

6.4.3. Command Line Arguments

Although actually a topic of its own, passing command line arguments to a program is an example of the usage of strings.

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

--- or ---

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

If we declare main as above, then the operating system’s shell will assign values to argc and argv based on what was typed at the command prompt to start running the program. The envp pointer points to the user’s environment variables.

  • argc is a counter for how many words were typed as part of the command to start the program. It is always at least one for the command itself.

  • argv is an array of pointers to strings (arrays of char). The last element in argv points to NULL.

    argv[0] --- the name of the program
    argv[1] --- first argument
    argv[2] --- second argument
    ...
    
  • envp is also an array of pointers to strings (arrays of char). The envp option is not required if the program only wishes to look at the arguments typed on the command line to start the program. The last element in envp points to NULL.

  • The structure of both argv and envp (array of pointers to read-only strings), can be viewed as follows.

    ../_images/argv.png

    Fig. 6.1 The program sees the command line arguments as an array of pointers to strings.

The following short program prints the contents of the command line arguments.

#include <stdio.h>

void show_strings( char ** );

int main( int argc, char **argv, char **envp )
{
   printf( "argc = %d\n",argc );
   printf( "argv[]::\n");
   show_strings( argv );
   printf( "envp[]::\n");
   show_strings( envp );
   return( 0 );
}

void show_strings( char **p )
{
   while( *p != NULL ) {
      printf( "\t%s\n", *p );
      p++;
   }
}