How do I write this in pointer notation?

A

Angela

//array notation works***********
char temp[]

for(int x=0; x<strlen(temp); x++)
{ temp[x]=(temp[x]*2); } //simple char encoding

//how do I do the same thing with pointer notation**********
char* temp

while( *temp )
{ *temp++= (*temp)*2; } //simple char encoding

I have played around with this and usually it just erases the first
few letters. If I wanted to do something like this with a C++ string,
is this possible?
 
L

lilburne

Angela said:
//array notation works***********
char temp[]

for(int x=0; x<strlen(temp); x++)
{ temp[x]=(temp[x]*2); } //simple char encoding

//how do I do the same thing with pointer notation**********
char* temp

while( *temp )
{ *temp++= (*temp)*2; } //simple char encoding

I have played around with this and usually it just erases the first
few letters. If I wanted to do something like this with a C++ string,
is this possible?


{ *temp++= (*temp)*2; } //simple char encoding

The *temp++ has the side effect of incrementing temp, so the
temp on the left is not the same as the temp on the right.

*temp++ *= 2;
 
A

Artie Gold

Angela said:
//array notation works***********
char temp[]

for(int x=0; x<strlen(temp); x++)
{ temp[x]=(temp[x]*2); } //simple char encoding

//how do I do the same thing with pointer notation**********
char* temp

while( *temp )
{ *temp++= (*temp)*2; } //simple char encoding

You cannot do it this way; the value of `temp' is being altered
without an intervening sequence point causing undefined behavior.

One correct option would be to mimic the array form, as in:

for (; *temp; temp++)
*temp = *temp * 2;
I have played around with this and usually it just erases the first
few letters.

Yes, due to the invocation of undefined behavior noted above.
If I wanted to do something like this with a C++ string,
is this possible?

Yes. Certainly. (Look up `iterator' and `transform', for example)

HTH,
--ag
 
A

Artie Gold

lilburne wrote:

[snip]
{ *temp++= (*temp)*2; } //simple char encoding

The *temp++ has the side effect of incrementing temp, so the temp on the
left is not the same as the temp on the right.

*temp++ *= 2;

Better than my original reply! (on this point)
--ag
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top