473,883 Members | 1,594 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pointer arithmetic

a
I am having trouble understanding the results of the following code:

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{

unsigned short *IO = reinterpret_cas t<unsigned short*>(0x8000) ;
unsigned short offset = static_cast<uns igned short>(0x2);
unsigned short *value = reinterpret_cas t<unsigned short*>(IO+offs et);

cout << "IO is " << hex << IO <<endl;
cout << "value is " << hex << value <<endl;

return 0;
}

The output for this case is: IO is 00008000, value is 00008004
I had expected value to be 00008002

If IO is not a pointer, I get the result I expected.

What is going on here?

Thanks to anyone with a helpful explanation.
Jul 19 '05 #1
6 6963
a wrote:
I am having trouble understanding the results of the following code:

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{

unsigned short *IO = reinterpret_cas t<unsigned short*>(0x8000) ;
This is really a bad idea...
unsigned short offset = static_cast<uns igned short>(0x2);
The cast in entirely unnecessary here. Never cast unless you absolutely
have to.
unsigned short *value = reinterpret_cas t<unsigned short*>(IO+offs et);
The cast is also unnecessary here.

cout << "IO is " << hex << IO <<endl;
cout << "value is " << hex << value <<endl;

return 0;
}

The output for this case is: IO is 00008000, value is 00008004
I had expected value to be 00008002
I get the same (after removing the unnecessary casts).

unsigned int is frequently 2 bytes on modern implementations . Because of
that, given a pointer to an unsigned int, adding 1 to that pointer has
to move it up 2 bytes to get to the next unsigned int. Likewise, adding
2 moves it up 4 bytes.

Basically, pointer arithmetic always works by translating:

p + n

(where p is a pointer and n is an integer) into:

p + n*sizeof(*p)

Of course, the second expression literally means something different to
the C++ language, but this is just a demonstration. The second is kind
of the compiler's interpretation. In your case, this translates to:

p + n*sizeof(unsign ed int)

or:

p + n*2

If IO is not a pointer, I get the result I expected.

What is going on here?


Pointer arithmetic.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #2
a wrote:
I am having trouble understanding the results of the following code:

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{

unsigned short *IO = reinterpret_cas t<unsigned short*>(0x8000) ;
unsigned short offset = static_cast<uns igned short>(0x2);
// no cast needed here unsigned short *value = reinterpret_cas t<unsigned short*>(IO+offs et);
cout << "IO is " << hex << IO <<endl;
cout << "value is " << hex << value <<endl;

return 0;
}

The output for this case is: IO is 00008000, value is 00008004
I had expected value to be 00008002

If IO is not a pointer, I get the result I expected.

What is going on here?

Thanks to anyone with a helpful explanation.

unsigned short *p = something;
unsigned short a;

// these two expressions are equivalent
a = p[5];
a = *(p+5);

The point is that when doing pointer arithmetic, the value that gets
added to the pointer value is multiplied by the size of the type pointed
to by the pointer. If it was different, the programmer would have to
worry about multiplying the offset by proper size and it would be really
inconvenient. Assuming that size of pointer == size of int the following
statement would be equivalent to the previous two:

int i = reinterpret_cas t<int>(p) + 5*sizeof(unsign ed short);
a = *reinterpret_ca st<unsigned short*>(i);

--
Ahti Legonkov

Jul 19 '05 #3
Kevin Goodsell <us************ *********@never box.com> wrote in message news:<mi******* **********@news read3.news.pas. earthlink.net>. ..
a wrote:
I am having trouble understanding the results of the following code:

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{

unsigned short *IO = reinterpret_cas t<unsigned short*>(0x8000) ;


This is really a bad idea...
unsigned short offset = static_cast<uns igned short>(0x2);


The cast in entirely unnecessary here. Never cast unless you absolutely
have to.
unsigned short *value = reinterpret_cas t<unsigned short*>(IO+offs et);


The cast is also unnecessary here.

cout << "IO is " << hex << IO <<endl;
cout << "value is " << hex << value <<endl;

return 0;
}

The output for this case is: IO is 00008000, value is 00008004
I had expected value to be 00008002


I get the same (after removing the unnecessary casts).

unsigned int is frequently 2 bytes on modern implementations . Because of
that, given a pointer to an unsigned int, adding 1 to that pointer has
to move it up 2 bytes to get to the next unsigned int. Likewise, adding
2 moves it up 4 bytes.


Presumably, wherever you've written "unsigned int" (here and later)
you meant "unsigned short". Just in case the OP was confused.

<snip>

GJD
Jul 19 '05 #4

"Ahti Legonkov" <le**@127.0.0.1 > wrote in message news:3f******** **@news.estpak. ee...
a wrote: The point is that when doing pointer arithmetic, the value that gets
added to the pointer value is multiplied by the size of the type pointed
to by the pointer.


Actually, it adds whatever it has to be to advance by that number of
objects. On word addressed machines adding 1 to a int pointer
literally adds 1 to the the internal value. On byte addressed machines
it does add sizeeof(int).
Jul 19 '05 #5
Gavin Deane wrote:
Kevin Goodsell <us************ *********@never box.com> wrote in message news:<mi******* **********@news read3.news.pas. earthlink.net>. ..

unsigned int is frequently 2 bytes on modern implementations . Because of
that, given a pointer to an unsigned int, adding 1 to that pointer has
to move it up 2 bytes to get to the next unsigned int. Likewise, adding
2 moves it up 4 bytes.

Presumably, wherever you've written "unsigned int" (here and later)
you meant "unsigned short". Just in case the OP was confused.


Yeah... Check the posting time for an explanation. ;)

Yes, every occurrence of 'unsigned int' should have been 'unsigned short'.

-Kevin (shouldn't post after 2 a.m.)
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #6
a

"a" <ag****@cox.net > wrote in message
news:QPV7b.4888 7$Qy4.7224@fed1 read05...
I am having trouble understanding the results of the following code:

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{

unsigned short *IO = reinterpret_cas t<unsigned short*>(0x8000) ;
unsigned short offset = static_cast<uns igned short>(0x2);
unsigned short *value = reinterpret_cas t<unsigned short*>(IO+offs et);

cout << "IO is " << hex << IO <<endl;
cout << "value is " << hex << value <<endl;

return 0;
}

The output for this case is: IO is 00008000, value is 00008004
I had expected value to be 00008002

If IO is not a pointer, I get the result I expected.

What is going on here?

Thanks to anyone with a helpful explanation.


Thanks to all for a nice explanation.

I do realize the casts were unneccesary (except the first, and it should be
noted that this is a piece of test code to a fixed address that will be
replaced with an OS function).
Jul 19 '05 #7

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

Similar topics

8
2195
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
12763
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...
6
2298
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; }
3
2213
by: randomtalk | last post by:
hello everyone! Well, recently i've been trying to pick up c and see what is pointer all about (been programming in lisp/python for the better part of my last two years).. mmm.. I'm currently reading The C Programming Language Second Edition.. When i hit on pointer arithmetic example, i have no idea what's happening, hopefully some of you could alleviate my confusion, so here goes:
27
9004
by: Erik de Castro Lopo | last post by:
Hi all, The GNU C compiler allows a void pointer to be incremented and the behaviour is equivalent to incrementing a char pointer. Is this legal C99 or is this a GNU C extention? Thanks in advance. Erik
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
3076
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...
41
3707
by: Summercool | last post by:
Can we confirm the following? also someone said, Java also has "reference" like in C++, which is an "implicit pointer": Pointer and Reference --------------------- I am starting to see what pointer and reference are and how they relate to each other.
19
3916
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
2029
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) {
0
9933
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
11114
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
10730
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
10835
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
10407
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...
0
7114
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
5982
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4205
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3230
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.