strcpy() and strcat() use in null terminated strings – CSKC
Sign In

Search

Code Learning #CPP#2611    siteicon   siteicon  

strcpy() and strcat() use in null terminated strings

Use of functions strcpy() and strcat() on null terminated strings.

Learning Objectives

  • Use of strcpy() and strcat() for copying and concatenation (addition) of null terminated strings.
  • Using the above functions directly with string literals or by another character arrays.

Source Code

TC++ #2611

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Code Understanding

char str1[20],str2[20],str3[]=” Cricket”;
Here three character arrays have been declared. The first have been given a fixed size of 20 chars andΒ  the last one str3 has also been initialised with the string literal. Its size will become as per the literal inserted into it.

char str4[50]=””; //This one is a larger char array space with 50 size but initialised to null character. Memory space of 50 chars will still be reserved in this case.

strcpy(str1,”Play”); //Here we are using strcpy where the string literal “Play” is being copied to str1. This function will perform well if str1 has sufficient space for given literal to be copied.

strcpy(str2,str3);
Here this is another way of strcpy where array already initialised in str3 is copied to str2

strcat(str4,str1);
Here we are try to add up or concatenate two strings where str4 will be added with str1 on its right side. Initially str4 has nothing (just null character) and added with str1 it will become Play.

strcat(str4,str2);
Here str4 is being further concatenated with str2, so now str4 will become Play Cricket

strcat(str4,” & Enjoy!”);
Here we are adding further with user provided string literal “& Enjoy!” so the content of str4 will become Play Cricket & Enjoy!

cout<<str4;Β 
The final output will be printed here. Remember that the programmer needs to ensure that before concatenation or copy the destination arrays should be of sufficient length.

Notes

  • Both strcpy() and strcat() functions can accidentally overwrite memory locations reserved for other variables or program areas if sufficient size is not allocated in advance. Modern programmers are thus advised to use function related to string class and get rid of such problems.

Common Errors

  • Array size allocation is the most common problem students may do. Pre-planning as per data size is required.


Suggested Filename(s): strcpy-strcat.cpp,cpycat.cpp



Share

Created: 13-Jan-2018 19:45 | Updated: 13-Jan-2018 19:49|