0

Hi,I have a question about pointers;

char * bf=new char[5];

char* p=bf+5;

Does p-- work? or will p-- make some undefined error? As bf+5 is undefined?

Thanks.

Tim Pierce
  • 5,514
  • 1
  • 15
  • 31
  • 3
    @RaviH: And what would that prove? – Fred Larson Jan 09 '14 at 05:55
  • It will prove whether that throws "some undefined error" or not. It is not a good way to learn programming without experimenting or trying such simple things first before asking question on stackoverflow. – RaviH Jan 09 '14 at 05:58
  • 6
    @RaviH It's possible for it to be undefined behavior and for the program to still execute without producing an error. Most users emphasize the fact that UB can make you fall out the sky or open a wormhole to pluto, but it's also allowed to just continue quietly, seemingly having succeeded until you try to run it in a different context. – ApproachingDarknessFish Jan 09 '14 at 05:59
  • 2
    @RaviH: Since it is not undefined behavior, it would work fine. Which would prove that it is either correct or it's undefined behavior. Undefined behavior does not throw "some undefined error." It can do almost anything, including seeming to work just fine. "Just try it" is not a valid test of undefined behavior. – Fred Larson Jan 09 '14 at 06:01
  • When someone is a passive learner he/she just asks questions. When someone is an active learner he/she tries it first and then (only then) if there is an unanswered question in mind will ask a question to clarify the thought. In this particular case expected behavior is very well documented. There is no "UB" (unexpected behavior). I believe this question was a way to find quick answers instead of learning/understanding the fundamentals of how pointers work. I don't have anything more to say in this matter. – RaviH Jan 09 '14 at 06:09
  • @RaviH: The code in [this link](http://ideone.com/Oa7TOC) compiles and does exactly what I expected it to (in this particular instance). Should I conclude then that the code is okay, and not undefined behavior? – Benjamin Lindley Jan 09 '14 at 06:29

2 Answers2

3

There is nothing undefined about

char* bf=new char[5];
char* p=bf+5;

But p will be pointing off the end of the array. As long as the array is not destroyed, p-- will bring you back to the last element of the array.

1

p-- in this case is guaranteed to point to the last element of the array, no UB.

ScarletAmaranth
  • 5,065
  • 2
  • 23
  • 34