Skip to main content
Engineering LibreTexts

8.5: Pointers and Arrays

  • Page ID
  • We very often use pointers with arrays. One example is the use of strings. We noted this in earlier work. Recall that the “address of” and array index “cancel each other” so that the following are equivalent:

    &somestring[0]    somestring

    Let’s look at an example of how you might use pointers instead of normal array indexing. We shall write our own version of strcpy() to copy one string to another. The function takes two arguments, the address of a source string and the address of a destination string. We will copy over a character at a time until we come to the null termination. First, the normal array index way:

    void strcpy1( char dest[], char source[] )
        int i=0;        /* index variable, init to first char */
        while( source[i] != 0 )     /* if it’s not null...*/
            dest[i] = source[i];    /* copy the char */
            i++;                    /* increment index */
        dest[i] = 0;                /* null terminate */

    Looks pretty straightforward, right? There are some minor improvements you can make such as changing the loop to while( source[i] ), but that’s not a big deal. Now in contrast, let’s write the same thing using pointers.

    void strcpy2( char *dest, char *source )
        while( *dest++ = *source++ );

    That’s it. Here’s how it works. dest and source are the starting addresses of the strings. If you say:

    *dest = *source;

    then what happens is that the value that source points to gets copied to the address referred to by dest. That copies one character. Now, to this we add the post increment operator ++:

    *dest++ = *source++;

    This line copies the first character as above and then increments each pointer. Thus, each pointer contains the address of the next character in the array (you’ve got to love that pointer math, this will work with any sized datum). By placing this code within the while() loop, if the content (i.e., the character copied) is non-zero, the loop will continue. The loop won’t stop until the terminating null has been copied. As you can imagine, the underlying machine code for strcpy2() will be much simpler, more compact, and faster to execute than that of strcpy1(). As was said at the outset of the course, you can do a lot in C with just a little code!

    • Was this article helpful?