fork download
  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5. /* Character arrays and string literals */
  6.  
  7. // Declaration of three arrays in the user data area, read and write permissions for the elements:
  8. char t1[] = {'H','e','l','l','o','\0'};
  9. char t2[] = "Hello";
  10. char t3[] = "Hello";
  11.  
  12. // Declaration of two pointers in the user data area, read and write permissions for the pointers
  13. // and allocation of the "Hello" literal (possibly) read-only
  14. char *s1 = "Hello"; // s1 points to 'H'
  15. char *s2 = "Hello"; // s2 likely points to the same place
  16.  
  17. void *v1 = t1, *v2 = t2, *v3 = t3, *v4 = s1, *v5 = s2;
  18. std::cout << v1 << '\t' << v2 << '\t' << v3 << '\t' << v4 << '\t' << v5 <<std::endl;
  19. // the result (v1, v2 v3 are different, v4 and v5 could be the same):
  20. // 0x23fe10 0x23fe00 0x23fdf0 0x404030 0x404030
  21.  
  22. // assignment to array elements:
  23. *t1 = 'a'; *t2 = 'b'; *t3 = 'c';
  24.  
  25. // modifying string literal: could be segmentation error:
  26. *s1 = 'd'; *s2 = 'e';
  27.  
  28. // The type of "Hello" is const char[6].
  29. // const char[] --> char* conversion is only for C reverse compatibility
  30. char *s3 = "Hello"; // warning: deprecated conversion from string constant to 'char*'
  31. const char *s4 = "Hello"; // correct way, no write permission through the pointer
  32. *s4 = 'f'; // syntax error, const-correctness is not flawed
  33.  
  34. return 0;
  35. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'int main()':
prog.cpp:14:14: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   char *s1 = "Hello";    // s1 points to 'H'
              ^
prog.cpp:15:14: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   char *s2 = "Hello";    // s2 likely points to the same place   
              ^
prog.cpp:30:20: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
         char *s3 = "Hello";  // warning: deprecated conversion from string constant to 'char*'
                    ^
prog.cpp:32:7: error: assignment of read-only location '* s4'
   *s4 = 'f';  // syntax error, const-correctness is not flawed
       ^
stdout
Standard output is empty