473,625 Members | 2,733 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

simple pointer question

Hi,

In the following code, can someone tell me the difference between *p++ and
p++ ? I can see both achieve the same result.

Thanks a lot !


#include <iostream>
using namespace::std;
int main() {
char *p = "test pointer";
while (*p) {
cout << *p;
*p++; // <<- What is the difference between *p++ and p++ (both achieve
the same result) ?
}
cout << endl;
return 0;
}
Jul 22 '05 #1
22 3279
"lokman" <lo****@fagi.ne t> wrote in message
news:c5******** **@nn-tk102.ocn.ad.jp ...
*p++; // <<- What is the difference between *p++ and p++ (both achieve
the same result) ?


p ++ increments the pointer, like you expect. *p ++ first dereferences
the pointer, and then increments it. Since the dereferenced temporary is not
assigned to anything, it is discarded.

hth
--
jb

(replace y with x if you want to reply by e-mail)
Jul 22 '05 #2
ak
On Sat, 17 Apr 2004 23:10:00 +0900, "lokman" <lo****@fagi.ne t> wrote:
Hi,

In the following code, can someone tell me the difference between *p++ and
p++ ? I can see both achieve the same result.

Thanks a lot !


#include <iostream>
using namespace::std;
int main() {
char *p = "test pointer";
while (*p) {
cout << *p;
*p++; // <<- What is the difference between *p++ and p++ (both achieve
the same result) ?
}
cout << endl;
return 0;
}


in this context there is no diff.

if you would for instance do a cout << *p++
then it would print p's current char and then
incr the ptr

*p get the value from the ptr
++ incr the ptr with whatever size of type it is.

/ak
Jul 22 '05 #3
"lokman" <lo****@fagi.ne t> wrote in message
news:c5******** **@nn-tk102.ocn.ad.jp ...
Hi,

In the following code, can someone tell me the difference between *p++ and
p++ ? I can see both achieve the same result.

Thanks a lot !


Ok,
p++ increments the pointer
*p gets the contents of the variable to which the pointer is pointing to

You could write in your loop
cout<<*p++<<end l;

Because of the precedence of the * operator so the *p is done before p++,
maybe it would be more clear if you wrote (*p)++ (don't use this in coding
this is just for you to understand you should write *p++ in your code)

Maybe an example of copying two strings;

char *s1="test";
char *s2="blab";

for(unsigned int i=0;i<strlen(s1 );i++)
*s1++=*s2++;

So the content of the s1 becomes the content of the s2;
Note that they are both the same size, if not you might have
undefined behavior.
But if you want to copy strign I would reccomed using <string>
rather than char*.

HTH
--
Frane Roje

Have a nice day

Remove (*dele*te) from email to reply
Jul 22 '05 #4
lokman wrote:
Hi,

In the following code, can someone tell me the difference between *p++ and
p++ ? I can see both achieve the same result.

Thanks a lot !
#include <iostream>
using namespace::std;
int main() {
char *p = "test pointer";
Quick note: don't do this. Never make a (non-const) char pointer point
to a string literal. This conversion is allowed for C compatibility, but
is deprecated because it is dangerous. It allows you to write code that
(attempts to) modify a string literal without getting a warning from the
compiler. Modifying a string literal (or attempting to) invokes
undefined behavior.

If you want a pointer to a string literal, always use a pointer to const
char, like one of the following:

const char *p = "some string";
char const *p = "some string"; // same as prev

const char * const p = "some string";
char const * const p = "some string"; // same as prev

In the last two 'p' itself is also const.
while (*p) {
cout << *p;
*p++; // <<- What is the difference between *p++ and p++ (both achieve
the same result) ?
}
cout << endl;
return 0;
}


It looks like all the replies so far are wrong in one way or another.
The expression 'p++' causes p to be incremented at some point before the
next sequence point. It also has a result, which is the value of 'p'
before being incremented. There's an subtle but important point here:
you don't know *when* 'p' will actually be updated, only that it will
happen sometime before the next sequence point (usually a semi-colon,
but there are others). People frequently get this wrong.

As for the expression '*p++', it is equivalent to '*(p++)' (contrary to
what one of the other replies said, post-increment has higher precedence
than dereference -- check any precedence chart). So, as described
previously, 'p' is scheduled to be incremented at some point before the
next sequence point, and also a result is given. The result is the value
of 'p' prior to the increment. The '*' is applied to that, giving the
object that 'p' pointed to prior to the increment. This result is
immediately discarded in your case.

So there's no reason for the '*' in this case. It might even slow your
program down a little, so get rid of it.

Also, replace 'p++' with '++p'. Get in the habit of using pre-increment
in cases where either will work. There's a chance it will be faster, and
it almost certainly won't be slower. There probably is no difference for
built-in types, but for class types there may be a substantial difference.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Jul 22 '05 #5
Jakob Bieling wrote:
"lokman" <lo****@fagi.ne t> wrote in message
news:c5******** **@nn-tk102.ocn.ad.jp ...

*p++; // <<- What is the difference between *p++ and p++ (both achieve
the same result) ?

p ++ increments the pointer, like you expect. *p ++ first dereferences
the pointer, and then increments it.


Nitpick: That sequence of events is not required.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Jul 22 '05 #6
Frane Roje wrote:
"lokman" <lo****@fagi.ne t> wrote in message
news:c5******** **@nn-tk102.ocn.ad.jp ...
Hi,

In the following code, can someone tell me the difference between *p++ and
p++ ? I can see both achieve the same result.

Thanks a lot !

Ok,
p++ increments the pointer
*p gets the contents of the variable to which the pointer is pointing to


Actually it gets the variable itself. "Contents of" sounds like a copy.

You could write in your loop
cout<<*p++<<end l;

Because of the precedence of the * operator so the *p is done before p++,
maybe it would be more clear if you wrote (*p)++ (don't use this in coding
this is just for you to understand you should write *p++ in your code)
(*p)++ has a completely different meaning than *p++.

Maybe an example of copying two strings;

char *s1="test";
char *s2="blab";
Make these const char *.

for(unsigned int i=0;i<strlen(s1 );i++)
*s1++=*s2++;


This is wrong or otherwise ill-advised in several ways.

1) The technically correct type to use is size_t.

2) Recalculating the length on each iteration is unnecessarily inefficient.

3) Prefer pre-increment to post-increment.

4) Modifying a string literal (which is a const object) gives undefined
behavior.

Besides that, the general approach is definitely not correct in general.
You'd need to check the relative length of the source string against the
available length of the destination buffer, then loop based on the
source string. If you knew the destination length was adequate, you
could just do this:

while (*dest++ = *src++) { continue; }

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Jul 22 '05 #7
while (*dest++ = *src++) { continue; }


Would you find this one less readable ?

while (*dest++ = *src++) ;

Benoit
Jul 22 '05 #8
Benoit Mathieu wrote:
while (*dest++ = *src++) { continue; }

Would you find this one less readable ?

while (*dest++ = *src++) ;


I find it less clear. A semi-colon in a place where they aren't usually
seen can be easily missed, making the reader think that the 'while'
controls (or is supposed to control) some statement that follows. It can
also look like an error, as if the programmer added the semi-colon at
the end of the line out of habit.

An explicit 'continue' statement removes all doubt about the intent.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Jul 22 '05 #9
"Kevin Goodsell" <us************ *********@never box.com> wrote in message
news:ri******** ***********@new sread2.news.pas .earthlink.net. ..
Frane Roje wrote: (*p)++ has a completely different meaning than *p++.
How?
Maybe an example of copying two strings;

char *s1="test";
char *s2="blab";


Make these const char *.

if they were const wouldn't that make then disabled for any kind of change?

for(unsigned int i=0;i<strlen(s1 );i++)
*s1++=*s2++;


This is wrong or otherwise ill-advised in several ways.


What is advised?(exepct for strcpy(), or maybe strncpy()(I'm not sure if
this one
exists))
1) The technically correct type to use is size_t. Isn't size_t actualy an unsigned integer?
3) Prefer pre-increment to post-increment. Why?

Besides that, the general approach is definitely not correct in general.
You'd need to check the relative length of the source string against the
available length of the destination buffer, then loop based on the
source string. If you knew the destination length was adequate, you
could just do this:


--
Frane Roje

Have a nice day

Remove (*dele*te) from email to reply
Jul 22 '05 #10

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

Similar topics

4
6301
by: trustron | last post by:
Hi all, I have got a pointer question. I was told that a pointer is a variable holding a memory address. SO:
5
1317
by: J | last post by:
Hi, I have an array: double *array = new double; Well, I have 2 actually.
7
355
by: questions? | last post by:
Let's say; char * first, *second; first=malloc(10*sizeof(char)); second=malloc(100*sizeof(char)); what would be the difference between first and second other than the difference in the address. I mean, when I use free() function to free the memory, how does the system know how large the block to free?
0
8253
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
8692
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8635
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...
0
8497
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6116
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5570
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4089
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...
0
4192
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2621
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

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.