C++: Char vs String initialization

#include "iostream"                           // a PREPROCESSOR directive 
using namespace std;
int main() // function header
{ // start of function body
using namespace std; // make definitions visible
char * t1 = new char;
*t1 = 'a';
cout<< "Case 1: " << t1 << "\n"; //Output: a. Valid output

char * t2;
//*t2 = 'a'; //Can also lead to bus error. Incase it is out of memory assigned to t2
//cout<< "Case 2: " << t2 << "\n"; //Output: a???. Garbled output, since you are trying to store 'a' in neverland

//char * t3;
//t3 = 'a'; // Compile error: myfirst.cpp:15: error: invalid conversion from 'char' to 'char*'

//char * t4;
//* t4 = "a"; // Compile error: myfirst.cpp:18: error: invalid conversion from 'const char*' to 'char'
// "a" is treated as string. 'a' is a character

char * t5;
t5 = "a";
cout<< "Case 5: " << t5 << "\n"; //Output: a. Valid Output, understand that here "a" is a string and that get space assigned in memory. On the other hand, 'a' does not get stored in memory when getting assigned to pointer. Also "a" is of type const char *, where 'a' is of type const char

int * fellow;
*fellow = 123; //Garbled output, bus error.
fellow = (int *)123; //fellow points to some location in memory and will result in bus error while we are accessing it.
return 0; // terminate main()
}

Comments