-1

I'm beginning to learn about pointers in C++ and wrote the below code to practice accessing elements in an array using them.

using namespace std;
char a[] = {'A', 'B'};  
char* p = a;

cout << "ARRAY IS " << sizeof(a) << " BYTES." << endl;
cout << "CHARACTER IS " << sizeof(a[0]) << " BYTES." << endl;
cout << "THEREFORE LENGTH IS " << (sizeof(a) / sizeof(char)) << " ELEMENTS." << endl << endl;

cout << "INDEX 0: " << *p << endl;
p++;
cout << "INDEX 1: " << *p << endl;
p++;
cout << "INDEX ?: " << *p << endl;
p++;
cout << "INDEX ??: " << *p << endl;

return 0;

I understand that the array is only two elements long, but tried incrementing the pointer anyway.

How come when I do this the ╟ character is printed to the console?

I'm using Visual Studio as my IDE.

Zeizz
  • 9
  • 1
  • 1
    The behaviour of your program is undefined - it could print anything, or nothing, or do something else entirely. –  Apr 10 '17 at 17:26
  • Accessing an array out of bounds is undefined behavior. That means anything could happen: crash, garbage, etc. – crashmstr Apr 10 '17 at 17:27

1 Answers1

-1

You happen to get that character because that's what is stored where p points. It is not guaranteed to be the same next time the programs runs, though.

p still points somewhere, just beyond the allocated array. In practice, I'd bet it's pointing at itself, since p is allocated right after the array.

donjuedo
  • 2,475
  • 18
  • 28
  • That downvote was quick. How about a comment to elaborate? – donjuedo Apr 10 '17 at 17:28
  • I didn't down vote, but your answer misses the most important part: the given code has undefined behavior. In the next run it *could* just print other garbage, but it would be equally legal for it to kill your cat (or the neighbours cat) – Daniel Jour Apr 10 '17 at 18:14
  • @DanielJour, I believe my second sentence hit that nail on the head. Maybe I was not clear enough about the reason. – donjuedo Apr 10 '17 at 18:59