Course Content
Programming in C
About Lesson

A string constant is an array of characters (terminated by a null character ‘\0’).

"Hello World!"

The number of bytes occupied by the string constant is thus one more than the number of characters between the double quotes.
When string constants are passed as an argument, for example in case of printf:

printf("Hello World!");

it gets accessed through a character pointer. printf receives a pointer to the beginning of the character array.

Let’s look at the following two definitions:

char astr[] = "Hello World!";
char *pstr = "Hello World!";

astr is an array, big enough to hold the sequence of characters and ‘\0’ that initialises it. Individual characters within the array may be changed but astr will always refer to the same storage. pstr is a pointer, initialised to point to a string constant; the pointer may be made to point elsewhere; results are undefined if we try to modify the string contents.

Let’s look at the following functions that attempt to copy a string from src to dest. Assigning

dst = src;

would just copy the pointer value (address), not the contents.
Let’s look at the simplest version first that uses array representation to copy every array element from src to dest and appends the null character ‘\0’ after the loop.

void strcpy1(char *dst, char *src)
{
  int i = 0;
  while(src[i] != '\0') {
    dst[i] = src[i];
    i++;
  }
  dst[i] = '';
}

We can improve on this and make use of the fact the src contains the null character as well.

void strcpy2(char *dst, char *src)
{
  int i = 0;
  while((dst[i] = src[i]) != '\0')
    i++;
}

We can use pointers directly to copy the string.

void strcpy3(char *dst, char *src)
{
  while((*dst = *src) != '\0') {
    src++;
    dst++;
  }
}

Instead of incrementing the two pointers inside the loop separately, we can just post-increment them during assignment.

void strcpy4(char *dst, char *src)
{
  while((*dst++ = *src++) != '\0');
}

Finally, we don’t need to explicitly check for the null character ‘\0’, as the loop would terminate when the expression evaluates to zero. So, we could further refine the code:

void strcpy5(char *dst, char *src)
{
  while((*dst++ = *src++));
}

Note: If we don’t use the extra parentheses in the strcpy5 code, the compiler gives a warning.

Scroll to Top