Dear Stack overflow community
I am learning C and C++, and I have some questions related to String pointers and Character arrays .
I have done a simple program:
void Strings (void)
{
char String1 [20];
cout<<"Please Enter your String1: "<<endl;
cin>>String1;
cin.ignore ();
cout<<String1<<endl;
}
- Created
String1 [20]
, character array of 20 elements - cout<<"Please enter your string1"
cin>>String1;
String1 acts as a pointer to the array, what ever I type it will be stored in String1,- Typed "ThisisaniceexampleofstringsinCpp" (34 characters)
- I compiled the program, and it crashed because the string I entered is more than 20 characters (makes sense).
I made the following changes to the program.
void Strings (void)
{
char*String0 = new char[20];
cout<<"Please Enter your String0: "<<endl;
cin>>String0;
cin.ignore ();
cout<<String0<<endl;
}
- I create a character pointer that points to an address in program memory of a space of 20 character element (like a character array of 20 elements
- Cout "Please enter your string"
- What ever string I type it will be stored in String0 (address pointer that points to a character array of 20 elements
- I type in "ThisisaniceexampleofstringsinCpp" (34 characters) and it got stored in String0 with no problems.
Why is it that char*String0 = new char[20]
a character pointer with space of 20 character element can store the 34 character string, but char String1 [20]
a character array of 20 elements can't store. shouldn't I get an error with both examples, as the string I entered is more than the space they hold/point to?
Thank you in advance.
Adam