Details the use of strcpy and strncpy string functions in c

  • 2020-06-12 10:03:46
  • OfStack

strcpy and strcnpy functions -- string copy functions.

1. strcpy function

char *strcpy(char *dst,char const *src) must make sure that the dst character space is large enough to hold src characters, otherwise the extra characters will still be copied, overwriting the value of the memory space that was originally stored at the end of the array. strcpy cannot determine this problem because he cannot determine the length of the character array.


 #include <stdio.h>
 #include<string.h>
 int main()
 {
 
  char message[5];
   int a=10;
  strcpy(message,"Adiffent");
  printf("%s %d",message,a);
  return 0;
 }

The output is Adiffent 10; So before you use this function, make sure that the target parameter is large enough to hold the source string

strncpy function: length limited string function

The function prototype: char *strncpy (char *dst, char const *src,size_t len) ensures that the string copied by the function ends with an NUL byte, which is 1 < len < sizeof(*dst)


 #include <stdio.h>
 #include<string.h>
 int main()
 {
  char message[5];
   int a=10;
  strncpy(message,"Adiffent",2);// The value of the length parameter should be limited to 1,5 ) 
  printf("%s %d",message,a); // Does not contain 1 and 5
  return 0;
 }

conclusion


Related articles: