1

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

rocambille
  • 15,398
  • 12
  • 50
  • 68
Embedded_Dude
  • 227
  • 3
  • 9
  • 2
    Writing past the boundary of a buffer is undefined behavior. By the virtue of being undefined, it can work or crash, or make volcanoes erupt. Better avoid it than ponder when it can work. – StoryTeller - Unslander Monica Oct 03 '16 at 11:43
  • It is [basically this](http://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why). – juanchopanza Oct 03 '16 at 11:44
  • 1
    Appearing to work is a valid form of undefined behavior. It's still undefined. Of course, the real solution would be to scrap the [tag:c] tag, and use `std::string` instead of raw pointers or arrays. – IInspectable Oct 03 '16 at 11:44
  • 1
    @StoryTeller @juanchopanza yes, I read about Undefined Behaviour, in the other post, I understand a bit now why it "Works". About `std::string` I am still learning C++ and haven't covered it, I will in the future. – Embedded_Dude Oct 03 '16 at 13:29

0 Answers0