473,703 Members | 2,808 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Jul 23 '05 #1
21 2078
MO******@gmail. com wrote:
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


I would say this is standard compliant (without looking it up). That said,
using p1 before incrementing is undefined (obviously).

Someone correct me if I'm wrong but all that has been done is p1 is set to
1*sizeof(char) before p. I say 1*sizeof(char) because it depends on the
size of a char on the system. For most systems, sizeof(char) is 1; so p1 is
intialised to 1 byte before p. If you use int instead of char, then it
would be 4 bytes (on my 32bit machine) before p.

But you don't need to be concerned with the particulars really, That's the
beauty of pointer arithmetic!

--
Alvin
Jul 23 '05 #2
Alvin wrote:

I would say this is standard compliant (without looking it up).
Then you'd better look it up. <g> The rule for pointer arithmetic is
that you can move around within an array or to one position past the
end. You can't go in front of the beginning.

For most systems, sizeof(char) is 1;


sizeof(char) is defined to be 1.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #3
Pete Becker wrote:
Alvin wrote:

I would say this is standard compliant (without looking it up).


Then you'd better look it up. <g> The rule for pointer arithmetic is
that you can move around within an array or to one position past the
end. You can't go in front of the beginning.

For most systems, sizeof(char) is 1;


sizeof(char) is defined to be 1.


I guess I didn't make myself clear. By standard compliant I was trying to
say p1 = p-1 was compliant. I didn't intend on saying the result was
compliant.

I guess what you are saying is the act of going in front of the array is
undefined.

--
Alvin
Jul 23 '05 #4
MO******@gmail. com wrote:
Is the following code cat main.cc #include <iostream>

int main(int argc, char* argv[]) {
char* p = new char[10];
char* p1 = p - 1;
p1 = p1 + 1;

if (p1 == p) {
std::cout << "Pointers are equal." << std::endl;
}

return 0;
}
g++ -Wall -ansi -pedantic -o main main.cc
./main Pointers are equal.
ISO C++ standard compliant?
No.
If yes, is it guaranteed that it will not crash on compliant platforms?
Who would guarantee that compliant code will not crash?
If yes, will it print "Pointers are equal." on any compliant platform?
It *will* print "Pointers are equal." on *every* compliant platform
even though the code itself is non-compliant.
Nobody guarantees that non-compliant code *will* crash either.
Will answers be the same if p points to local memory or string literal? cat main.cc #include <iostream>

int main(int argc, char* argv[]) {
const
char* p = "Pointers are equal.";
char* p1 = p - 1;
p1 = p1 + 1;

if (p1 == p) {
std::cout << "Pointers are equal." << std::endl;
}

return 0;
}
g++ -Wall -ansi -pedantic -o main main.cc

main.cc: In function `int main(int, char**)':
main.cc:6: error: \
invalid conversion from `const char*' to `char*'

Why couldn't you perform this simple experiment yourself?
Your compiler will answer most of these questions.
Next time, please show us the results from your experiments
and convince us that you are *not* just another lazy programmer.
Jul 23 '05 #5
<MO******@gmail .com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
Is the following code ISO C++ standard compliant?


It's not compliant, but I'd honestly be amazed if you could find me a
compiler/runtime environment combination that failed to run it and give you the
output you expect.

- JFA1
Jul 23 '05 #6

Pete Becker wrote:
Then you'd better look it up. <g> The rule for pointer arithmetic is
that you can move around within an array or to one position past the
end. You can't go in front of the beginning.


Your comment seems to imply that there's something checking the end
points of the array. There is not. You *can* go in front. You can
even do pointer arithmetic on a pointer that's not even pointing to an
array. It compiles, ( but that doesn't mean it doesn't produce
undefined behavior ).

-Brian

Jul 23 '05 #7
"James Aguilar" <jf**@cec.wustl .edu> wrote in message
news:d4******** **@newsreader.w ustl.edu...
<MO******@gmail .com> wrote in message It's not compliant, but I'd honestly be amazed if you could find me a
compiler/runtime environment combination that failed to run it and give
you the output you expect.


There was an implementation a number of years ago that would terminate such
programs with a diagnostic message. However, I don't think that the company
that produced that implementation is still in business, nor do I know what
other implementations might behave the same way.
Jul 23 '05 #8

E. Robert Tisdale wrote:
Why couldn't you perform this simple experiment yourself?


Actually I checked it on Visual C++ 6.0 and gcc on Solaris and Linux
and got the expected results.
However, the point of my questions was to figure out if it was a safe
practice to use it on arbitrary platform and what ISO standard said
about it.

So from what I hear it is a bad idea to use the code like this for
multi platform development (even though the probability to get in
trouble is low).

Michael

Jul 23 '05 #9
BigBrian wrote:

Your comment seems to imply that there's something checking the end
points of the array.
Nope.
There is not. You *can* go in front. You can
even do pointer arithmetic on a pointer that's not even pointing to an
array. It compiles,


Not necessarily. The behavior is undefined, and that means you cannot
count on anything in particular. There is nothing in the language
definition that requires this code to compile. Don't use compilers to
test code conformance.

By the way, when most people say "you can't to that" there's an implied
"in conforming code."

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2186
by: ceo | last post by:
Hi, Following is a program that doesn't give the expected output, not sure what's wrong here. I'm adding the size of derived class to the base class pointer to access the next element in the array. Why does bp point to some address that is not &d? Please clarify. Thanks,
22
12730
by: Alex Fraser | last post by:
From searching Google Groups, I understand that void pointer arithmetic is a constraint violation, which is understandable. However, generic functions like qsort() and bsearch() must in essence do exactly this, and similarly generic functions seem to have useful applications. In a few posts I read, it was suggested to avoid void pointer arithmetic by casting to a char pointer, and performing arithmetic on that (in multiples of...
3
7654
by: sathyashrayan | last post by:
The standard confirms that the following initialization of a struct struct node { --- --- } struct node var = {NULL};
6
2286
by: Francois Grieu | last post by:
Are these programs correct ? #include <stdio.h> unsigned char a = {1,2}; int main(void) { unsigned char j; for(j=1; j<=2; ++j) printf("%u\n", *( a+j-1 )); return 0; }
7
528
by: barikat | last post by:
int a; int *Ptr1, *Ptr2; Ptr1 = a; Ptr1++; Ptr2 = a; printf("Ptr1 : %p\n", Ptr1); printf("Ptr2 : %p\n\n", Ptr2);
26
3052
by: Bill Reid | last post by:
Bear with me, as I am not a "professional" programmer, but I was working on part of program that reads parts of four text files into a buffer which I re-allocate the size as I read each file. I read some of the items from the bottom up of the buffer, and some from the top down, moving the bottom items back to the new re-allocated bottom on every file read. Then when I've read all four files, I sort the top and bottom items separately...
19
3897
by: =?iso-8859-1?b?VG9t4XMg0yBoyWlsaWRoZQ==?= | last post by:
Coming originally from C++, I used to do the likes of the following, using a pointer in a conditional: void Func(int *p) { if (p) { *p++ = 7; *p++ = 8;
25
2008
by: Ioannis Vranos | last post by:
Are the following codes guaranteed to work always? 1. #include <iostream> inline void some_func(int *p, const std::size_t SIZE) {
8
1862
by: tfelb | last post by:
Hey group! I have 2 questions. I saw functions with char *dst = (char *)src. In that case if I remember what I've learned I assign (an) (the) address of src to dst. Right? But I can assign an address with the address operator & too? char *dst = &src. What's the difference between *dst = (char *)src and *dst = &src and
0
8739
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8652
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9089
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8983
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7831
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4412
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3107
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2402
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2036
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.