Home > Back-end >  Ask the strncpy code is how to realize the function
Ask the strncpy code is how to realize the function

Time:09-25

Void strncpy (String & amp; To the const String & amp; The from, int n)

/* Post: The function concatenates The String add_on onto The end of The String add_to.

*/

{
Const char * cfrom=from the c_str ();
Char * copy=new char [n].
To=strncpy (copy, cfrom, n);
The delete [] copy;
}

CodePudding user response:

At the end of the execute when the strncpy, cfrom has copy to copy the content of the variables,
Strncpy return values of copy, assigned to the to,

CodePudding user response:

Char * strncpy (char * dest, char * SRC, int n)

To=strncpy (copy, cfrom, n);//to a pointer variable pointing to copy an array
The delete [] copy;//delete later to unsafe

But here is to type String, the to=strncpy (copy, cfrom, n); Will construct a String object? Think not write clear,

CodePudding user response:

Char * copy=new char [n].
Seems to be the n + 1

CodePudding user response:

Copy to end, to be on the safe side, it is best to dest NULL string of the last character

CodePudding user response:

This is a definition of the String class a strncpy function, the strncpy () function principle is by calling the C function implementation,
Code comments are as follows:

Void strncpy (String & amp; To the const String & amp; The from, int n)
{
Const char * cfrom=from the c_str ();//copies for String into c_str
Char * copy=new char [n].//create a new block size for an array of strings n
To=strncpy (copy, cfrom, n);//strncpy function called copy cfrom to copy an array of strings, and at the same time will produce an array of strings
//assigned to the String object to a type conversion has happened here, so
//the equal sign here to override in the class, otherwise not achieve
The delete [] copy;//good programming habits, function application by the function of space for maintenance, exits should delete
}

Ps: this is not the final exams ╭ studying ╮ (︶ ︿ ︶) ╭ studying ╮
  • Related