GOEDUHUB Tutorials    ||    AI    ||    ML  ||    NLP    ||    OpenCV    ||    Python    ||    OOPS    ||    DBMS    ||    DSA    ||    JAVA    ||    Linux    ||    C Programming
7976731765 Go To Your University       ||       Placement Preparation       ||        Technical-MCQ and Interview Questions
Online Live Classes Youtube Live Link
0 like 0 dislike
17 views
in Tutorial & Interview questions by Goeduhub's Expert (8.1k points)

 Copy and Concatenation: strcpy(), strcat()

1 Answer

0 like 0 dislike
by Goeduhub's Expert (8.1k points)
 
Best answer

#include <stdio.h> 

#include <string.h>

int main(void) 

{                   /* Always ensure that your string is large enough to contain the characters   * and a terminating NUL character ('\0')!   */  

char mystring[10];

  /* Copy "foo" into `mystring`, until a NUL character is encountered. */  

strcpy(mystring, "foo");  

printf("%s\n", mystring);

  /* At this point, we used 4 chars of `mystring`, the 3 characters of "foo",   * and the NUL terminating byte.   */

  /* Append "bar" to `mystring`. */  

strcat(mystring, "bar");  

printf("%s\n", mystring);

  /* We now use 7 characters of `mystring`: "foo" requires 3, "bar" requires 3   * and there is a terminating NUL character ('\0') at the end.   */

  /* Copy "bar" into `mystring`, overwriting the former contents. */  

strcpy(mystring, "bar");  

printf("%s\n", mystring);

return 0; 

}

Outputs:

foo foobar bar

If you append to or from or copy from an existing string, ensure it is NUL-terminated!

String literals (e.g. "foo") will always be NUL-terminated by the compiler. 

 Goeduhub:

About Us | Contact Us || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 
 Placements:   List of companies | Logical Reasoning Questions | Quantitative Aptitude Questions | General English Questions | Technical-MCQ and Interview Questions
 Important Lists: List of NITsList of IITsList of Exams After Graduation | List of Engineering Entrance Examinations (UG/PG)College ReviewsCollege Fest, Events & WorkshopsKnowledge ShareTrainees/Interns After 15-04-2020
Exams & Cutoffs: JEE Main | JEE Advanced | GATE | IES | ISROList of PSUs || Cutoff-GATECutoff_IIT-JEECS-ScopeECE ScopeEE-Scope
 Download Previous Year Papers For:  GATE | IES | RAJASTHAN TECHNICAL UNIVERSITY (RTU-Kota)RPSC Technical Exams | ISRO
...