 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
MOvetsky@gmail.com Guest
|
Posted: Wed Apr 27, 2005 8:51 am Post subject: Pointer arithmetic questions |
|
|
Is the following code ISO C++ standard compliant?
If yes, is it guaranteed that it will not crash on compliant platforms?
If yes, will it print "Pointers are equal" on any compliant platform?
Will answers be the same if p points to local memory or string literal?
char *p = new char[10];
char *p1 = p-1;
p1 = p1 + 1;
if(p1 == p)
{
cout << "Pointers are equal" << endl;
}
Thank you,
Michael
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Maciej Sobczak Guest
|
Posted: Thu Apr 28, 2005 12:29 pm Post subject: Re: Pointer arithmetic questions |
|
|
Hi,
[email]MOvetsky (AT) gmail (DOT) com[/email] wrote:
| Quote: | Is the following code ISO C++ standard compliant?
|
No. (5.7/5)
This results in undefined behaviour.
--
Maciej Sobczak : http://www.msobczak.com/
Programming : http://www.msobczak.com/prog/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Ali Çehreli Guest
|
Posted: Fri Apr 29, 2005 1:40 am Post subject: Re: Pointer arithmetic questions |
|
|
<MOvetsky (AT) gmail (DOT) com> wrote
| Quote: | Is the following code ISO C++ standard compliant?
|
Yes, provided that the names cout and endl are brought to scope earlier in
the code It has undefined behavior though.
| Quote: | If yes, is it guaranteed that it will not crash on compliant platforms?
|
It may crash.
| Quote: | If yes, will it print "Pointers are equal" on any compliant platform?
|
It may print that.
| Quote: | Will answers be the same if p points to local memory or string literal?
|
Irrelavent.
| Quote: | char *p = new char[10];
char *p1 = p-1;
|
Undefined behavior above.
Pointer arithmetic makes the pointer point to other objects. p currently
points to the first newly allocated char. Since there is no char before the
"first newly allocated char," that is undefined behavior.
Having said that, I think the code will work with some compilers; because
some of them store some house cleaning data right before the area allocated
for the objects. That extra data keeps information like the number of
objects that was passed to new[], to be used when delete[] is called.
| Quote: | p1 = p1 + 1;
if(p1 == p)
{
cout << "Pointers are equal" << endl;
}
|
Ali
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|