String Basics


Defining an automatic string: It is defined within a block or within the whole file. Memory allocation and deallocation is controlled automatically by the system -- allocate when it is declared, and deallocatte on leaving the block.


Creating a string:


A string function example: Here is a function which reads in a string from standard input. The idea is to read in one character at a time until a newline is found, and then put in the string terminator character.

Notes:


Here is a test program for getline:

Sample output:



A complete set of test would consist of:

Why didn't we write the test program with MAXLINE 1000?

Here is another version of getline

Notes:


String copy functions:

Notes:


Strings and Pointers:

When managing a string, one must remember that it is an array of char.  But, when passing a string, the formal heading of the function could be either of the headings below.

In either case the string can be manipulated like an array...or like a pointer.  (This holds true for any array also.)

However, there is a tremendous difference between the following:

Notes:

There is also a tremendous difference between the following:

Notes:


<string.h>

The following functions are found in <string.h>


There are more...

From the manual


To control input, error handling can be done using some useful functions in <stdlib.h>. You will notice from time to time that if you enter a string instead of a number (as a program may be expecting) the string will crash your program.  To avoid this, input everything as a string and convert to values as you see fit.

Here are some helpful functions.


Run this to see dangerous usage of string function.


So how can we avoid string overflow???


Copyright © 2011, Neal R. Wagner. Permission is granted to access, download, share, and distribute, as long as this notice remains.