Copying Strings

Sometimes you'll need to create a copy of a string in an application so that you can manipulate the value without affecting the original. When you work with strings and pointers, you have two ways of copying strings. The first method makes use of the strncpy() function:

strncpy(string1, string2, length);

Once again, the length value should correspond to the available room in string1. This function makes a literal copy of the value of string2 and assigns this to string1.

The strncpy() is fine when you want a second copy of a string, but it does require twice the memory, as that second string must also be stored. If you want to work with a second reference to a string value instead, you can copy a string pointer:

char *string1 = "Sophia";
char *string2;
string2 = string1;

The string1 variable is a pointer to the location in memory where the literal string Sophia is stored. The string2 variable is also a pointer to this same location. The end result is two pointers—each of which requires very little memory—that can point to the same string value. This also means that a change to the string value through either pointer will be visible when the string is read through the other pointer, because only one string is really being stored.

In our next example, several words will be read in from the keyboard and stored in memory. The strncpy() function will help make this process possible.

To copy a string

1.
Create a new file or project in your text editor or IDE.

2.
Type the standard beginning lines of code (Script 11.5):

/* copy.c - Script 11.5 */
#include <stdio.h>

Script 11.5. This application reads in up to 10 (NUM_STRINGS) words of 10 (STR_LEN) characters in length, copying them each into an array.


3.
Include the string.h header:

#include <string.h>

For this application, string.h is required since it defines the strncpy() function.

4.
Add a function prototype:

void discard_input (void);

This application will also make use of the discard_input() function, as did the guessing game.

5.
Set two constant macros:

#define NUM_STRINGS 10
#define STR_LEN 10

The words entered by the user will be stored in a multidimensional character array whose parameters are set by these constants. The application will take up to NUM_STRINGS words, each of which can be up to STR_LEN characters long.

6.
Begin the main function:

int main (void) {

7.
Define two character arrays:

char words[NUM_STRINGS][STR_LEN];
char input[STR_LEN];

The first array will store all of the submitted words. The second character array will be used to retrieve the keyed input.

8.
Define two integers:

int i;
int count = 0;

The i variable is a loop counter. To track the total number of words the user entered—which can be up to 10, the count variable will be incremented.

9.
Define a for loop:

for (i = 0; i < NUM_STRINGS; ++i) {

To read in all 10 words, a loop will be used. This iterates from 0 to 1 less than NUM_STRINGS.

10.
Prompt for and read in a word:

printf("Enter a word (or 0 to quit):
 ");
scanf("%9s", input);
discard_input();

A word will be read in of up to 9 characters in length (allowing for the tenth available spot to be filled with ). The read-in value is assigned to the input character array and then any extraneous input is discarded.

11.
Check that the user didn't type a 0:

if (input[0] == '0') break;

If the user wants to exit the application and enter no more words, they can indicate this by entering 0 (see the prompt, Figure 11.12). This conditional then checks if the first character in the input array is equal to 0. If so, the break will exit the for loop (it has no effect on the if conditional). Since the break is the only if statement, curly braces can be omitted for brevity.

Figure 11.12. The application's prompt indicates how the user can terminate the application.


Another way to write this condition would be to use

if (strncmp(input, "0", 1) == 0)
 break;

In that code, 0 is within double quotation marks, as you must compare two strings. In the application's code, 0 is within single quotation marks, as it is comparing the first character in input to the character 0.

12.
Copy the inputted word into the array:

strncpy(words[i], input, STR_LEN);

With each iteration of the loop, the input variable will be replaced with a new word. Therefore, the original value will be copied over to the words array. By using i—the loop counter—as its index, we ensure that each entered word will populate the next available spot in the array.

Even though we know that input is at most 9 characters long, the third argument in strncpy() is set to STR_LEN so that buffer overflow cannot occur.

13.
Complete the while loop:

   ++count;
}

The count variable will be used to count the number of submitted words, so its value is incremented by 1.

14.
Print the number of submitted words.

printf("A total of %d words was
 entered.
", count);

15.
Complete the main function:

   getchar();
   return 0;
}

16.
Define the discard_input() function:

void discard_input (void) {
    char junk;
    do {
            junk = getchar();
    } while (junk!= '
'),
}

17.
Save the file as copy.c, compile, and debug as necessary.

18.
Run the application (Figures 11.13 and 11.14).

Figure 11.13. The application reads up to 10 words, or until the user enters a 0. The number of read words is then displayed.


Figure 11.14. The application automatically stops reading in words once 10 have been entered.


✓ Tips

  • The strncpy()function will not copy the terminating character if string2 has length or more characters in it. For this reason, after making a copy, you should make the last character of the new string1 equal to . Thus, the proper code for using strncpy() can look something like this (where LENGTH is a C preprocessor macro):

    strncpy(string1, string2, LENGTH-1);
     string1[LENGTH-1] = '';
    

    In the previous example, this was not an issue as we knew that string2 would have a terminating on it already (because it was limited from the keyboard input).

  • The strncpy() function can be used to assign a value to a string, without using a second string variable:

    char string1[10];
    strncpy(string1, "Sophia",
     strlen(string1));
    

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset