Strings

In C/C++ a string is an array of char but is assumed to be null terminated.

All the functions that work with strings assume that they are null-terminated. So just like arrays, you have to be careful and do your own error checking to make sure that you do not reference outside of the allocated space for the string.

String Values

String values are easiest to declare within double quotes:

	char clown[] = "bozo";       //Compiler figures out size
The size is the number of characters plus 1 for the null terminator. We can alternately declare the above string as follows:
    char clown[5] = {'b', 'o', 'z', 'o', '\0'};

    or

    char clown[] = {'b', 'o', 'z', 'o', '\0'};

A Few Demos to Look at

strlen.cpp

strlen2.cpp

stringDemo.cpp

Pointers

You can think of computer memory as a huge array of bytes.

We call each "index" an address.

Definition of a pointer

If pointer values are addresses, how do we come up with address values in the first place? What is the analog of a constant for an address?

NULL

NULL is a special predefined pointer value that points to nothing. We won't use it much for now, but it will be quite useful later so keep it in the back of your mind. Note also that NULL is actually just a 0, so we can test against 0 for NULL.

& operator

We can express the address of any variable by making use of the &:


    int i;
    double x;

    ... &i ...
    ... &x ...
In C/C++, when you declare a pointer, you must also declare what type it points to.

    int bozo;    //an int
    int *ip;     //ptr to an int
    ip = &bozo;
    *ip = 5;
So, once ip = &bozo executes, *ip = 5 and bozo = 5 are the same.

How to interpret

Syntax

Make sure that you see the demo pointer1.cpp and run it!

To Index Previous Next