String | Memory Copy

Wednesday 8 May 2013

Based on experience, I'm used to making programs using only integers in inputting choices or just doing plain mathematics but I thought that making programs doesn't just revolve around numbers it also has characters such as letters and symbols. That's when I encountered string and array.

String is used when you have to input a lot of characters or simply a phrase or sentence. On the other hand, array is used as a large storage of your inputs either characters or numbers. In this program, we are going to copy a value from one memory to another using string, array and the memcpy command. In this example, string1 will copy the value of string2. The string value would be, "This is a string.". Check out the codes below.


   1:  #include<iostream>
   2:  #include<conio.h>
   3:  #include<cstring>
   4:   
   5:  using namespace std;
   6:   
   7:  main()
   8:  {
   9:        char str1[20];
  10:        char str2[]="This is a string.";
  11:     
  12:        cout<<"Before memcpy()\n\nstr1 contains: "<<str1<<endl<<"str2 contains: "<<str2<             <endl<<endl;
  13:        memcpy(str1,str2,17);
  14:        cout<<"After memcpy()\n\nstr1 contains: "<<str1<<endl<<"str2 contains: "<<str2<<             endl;
  15:   
  16:        getch(
  17:   }



When you run the program it will automatically show you the output, there will be no need to input. It will show you the difference between the two strings. In before memory copy (memcpy), string1 (str1) shows random letters and symbols because the value of string1 is not specified in the array declaration, it only have a limited memory (char str1[20];). While string2 (str2), shows the phrase, "This is a string.", because it is already declared inside the array (char str2[]="This is a string.";).

Now, after memory copy you will observe that string1 and string2 has the same outputs. It's because string1 copied the declared string in string2 using memcpy command. Check out the output below.



Hope you learned something. Please, feel free to leave a comment below. Thanks!

No comments:

Post a Comment

Please do leave a comment. It's gonna be a friendly conversation between programmers. Hope you do find our blog helpful. Thank you!

Related Posts Plugin for WordPress, Blogger...