Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Functions strcpy and strncpy

September 12, 2013 Posted by: GPA Views: 785 0 comments

Problem

What is the difference between strcpy and strncpy in C programming?

Solution

In this article, you will know  difference between strcpy and strncpy. We'll write simple program using these functions.  You need include header file <string.h> for this program.

Declaration:

char *strcpy( char * firstString , const char * secondString );

This function copies its second argument secondString into its first argument firstString.

char *strncpy( char * firstString , const char * secondString , size_t n );

Function strncpy is equivalent to strcpy, except that strncpy specifies the number of characters (n) to be copied from the string into the array.  It adds null termination at the end of the target string. Terminating null character is written only if the number of characters to be copied is at least one more than the length of the string. For example, if "hello" is the second parameter, a terminating null character is written only if the third parameter to strncpy is at least 6 (five characters in "hello" plus  '\0').

Example:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//main function
int main(int argc, char *argv[]){
   printf("globalproganswer.com\n");
  char firstString[50];//first parameter
  char secondString[] = "The difference between strcpy and strncp";//second parameter
  printf("\nResult of strcpy function\n");
  printf( "The string in array secondString is: %s\nThe string in array firstString is: %s\n",
 secondString,strcpy(firstString, secondString));//call function strcpy
  //Example with function strncpy
  char strncpyArray[50];
  //copy first 10 characters of firstString into strncpyArray.   strncpy(strncpyArray, firstString, 10);//call function strncpy   strncpyArray[10]='\0';//terminate string in strncpyArray
  printf("\nResult of strncpy function\n");
  printf( "The string in array strncpyArray is: %s\n\n",strncpyArray );
   system("PAUSE");//delay
  return 0;
}

Output

Function strcpy and strncpy

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe