fork(1) download
  1. #include <iostream>
  2.  
  3. class MSG
  4. {
  5. public:
  6. std::string title;
  7. std::string msg;
  8. };
  9.  
  10. void c_way( int cLinesMax )
  11. {
  12. // Allocate Memory
  13. MSG *pmsg = (MSG *)malloc( cLinesMax * sizeof(MSG) );
  14.  
  15. // Set MSG Values
  16. for( int i = 0; i < cLinesMax; i++ )
  17. {
  18. pmsg[i].title = "C TITLE ";
  19. pmsg[i].title += std::to_string( i+1 );
  20. pmsg[i].msg = "C MESSAGE ";
  21. pmsg[i].msg += std::to_string( i+1 );
  22. }
  23.  
  24. // Print MSGs
  25. for( int i = 0; i < cLinesMax; i++ )
  26. std::cout << pmsg[i].title << " : " << pmsg[i].msg << std::endl;
  27.  
  28. // Delete Allocated Memory (deallocate)
  29. free( pmsg );
  30. }
  31.  
  32. void cpp_way( int cLinesMax )
  33. {
  34. // Allocate Memory
  35. MSG *pmsg = new MSG[cLinesMax];
  36.  
  37. // Set MSG Values
  38. for( int i = 0; i < cLinesMax; i++ )
  39. {
  40. pmsg[i].title = "CPP TITLE ";
  41. pmsg[i].title += std::to_string( i+1 );
  42. pmsg[i].msg = "CPP MESSAGE ";
  43. pmsg[i].msg += std::to_string( i+1 );
  44. }
  45.  
  46. // Print MSGs
  47. for( int i = 0; i < cLinesMax; i++ )
  48. std::cout << pmsg[i].title << " : " << pmsg[i].msg << std::endl;
  49.  
  50. // Delete Allocated Memory (deallocate)
  51. // delete: deallocates one MSG instance
  52. // delete[]: deallocates all MSG instances in array
  53. delete[] pmsg;
  54. }
  55.  
  56. int main( int argc, char *argv[] )
  57. {
  58. int cLinesMax = 0;
  59. std::cout << "set array size: ";
  60. std::cin >> cLinesMax;
  61. std::cout << std::endl;
  62.  
  63. c_way( cLinesMax );
  64. cpp_way( cLinesMax );
  65.  
  66. return 0;
  67. }
  68.  
Success #stdin #stdout 0s 16064KB
stdin
3
stdout
set array size: 
C TITLE 1 : C MESSAGE 1
C TITLE 2 : C MESSAGE 2
C TITLE 3 : C MESSAGE 3
CPP TITLE 1 : CPP MESSAGE 1
CPP TITLE 2 : CPP MESSAGE 2
CPP TITLE 3 : CPP MESSAGE 3