I have declared and initialized a string in char* like below:
int length;
cout<<"Enter string length: ";
cin>>length;
char* str = new char[length];
cout<<"Enter your string here:";
for(int i = 0;i < length;i++)
cin>>str[i];
cout<<str<<endl;
Compile using DevC++, it give me what I type there, but in Visual C++ it print out string with some random character at the end.For example; I type "hello" Visual C++ give me:"hello ^^&*(Y&".Can someone explain to me why does this happen ?
You're not null terminating the string. You need to assign a char array of length + 1
to allow room for the null character at the end of the string.