In depth analysis of strcat function and strncat function

  • 2020-04-02 01:03:53
  • OfStack

Function prototype: extern char *strcat(char *dest,char * SRC)
Argument description: dest is a pointer to a destination string, that is, the concatenated string (first), and SRC is a pointer to a source string (last).
Library name: #include < String. H >
Functions: The string referred to by SRC is added to the end of dest to realize the concatenation of the string, and the concatenation overrides the '/0' at the end of dest.
Return instructions: The memory area indicated by SRC and dest must not overlap, and the dest must have enough space to hold the SRC string to return a pointer to the dest.
Other notes: Not for the time being.
Example:

#include<string.h>
#include<stdio.h>
int main()
...{
    char dest[100]="Hello,I am sky2098,I liking programing!";  //Here we've carved out 100 bytes of space, which is much more than the size of the string
    char *src="gramk";
    char *temp;
    temp=strcat(dest,src);
    if(temp!=NULL)
    ...{
        printf("%s",temp);
    }
    else
    ...{
        printf("You cause an error!");
    }
    return 0;
}

VC++ 6.0 compile run:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013053116335427.jpg ">

If space is initially insufficient for dest, as we did:
Char *dest="Hello,I am sky2098,I liking programing!" ;
An exception occurs when a string is concatenated:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013053116335428.jpg ">

Char *dest="Hello,I am sky2098,I liking programing!" ; We just allocated strlen("Hello,I am sky2098,I liking programing!") for dest. ) + 1; The connection is overwritten on dest's "/0" and there is only one "/0" space, so the connection cannot be implemented.
Function prototype: Extern char *strncat(char *dest,char * SRC,int n)
Parameter description:
SRC is the source string, dest is the destination string, and n is the first n characters in the specified SRC.
Library name: #include < String. H >
Functions: Add the first n characters of the string SRC refers to to the end of dest, overwrite the '/0' at the end of dest, and realize string concatenation.
Return instructions: Returns a pointer to the concatenated string.
Other notes: Not for the time being.
Example:


#include <string.h>
#include <stdio.h>
int main()
...{
    char str1[100]="SKY2098,persist IN DOING AGAIN!";
    char *str2="sky2098,must be honest!";
    int n=15;
    char *strtemp; 
    strtemp=strncat(str1,str2,n);   //Concatenate the first n characters in the string str2 to the end of str1
    printf("The string strtemp is:  %s  ", strtemp);
    return 0;
}

In vc + + 6.0   Compile and run:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013053116335429.jpg ">

Implements the operation of specifying a concatenation of characters in one string to another string.


Related articles: