1
\$\begingroup\$

I am trying to run through a sequence of memory and display it on the command window. Here is the code:

int addr[10];              //Address addr is 32 bit
for{int i=0 ; i<10 ; i++}
{
  int *p = &addr[i];        //Pointing to the 32 bit addresses from 0 to 9
  cout<<p<<endl;            //Display the pointed addresses
}
return 0;
 }

Output:

 002AF948             //address of addr[0]
 002AF94C            //address of addr[1]
 002AF950            //address of addr[2]
 ....upto i = 9

Question: In the output, Isn't the address of addr[1] supposed to be 002AF949 instead of 002AF94C?. Why is it skipping the memory addresses 002AF49, 002AF4A, 002AF4B and then displaying addr[1] address as 002AF94C?. The same thing happens with addr[2] also.

Why is the pointer skipping these intermediate 32 bit addresses when incremented?

\$\endgroup\$
3
\$\begingroup\$

Since i is declared as int it will take 4 bytes to store each value of i. Since each address corresponds to a single byte, it will take 4 locations to store an int.

In your case,

It will take memory range 002AF948 - 002AF94B to store 0 (0x00000000)

It will take memory range 002AF94C - 002AF94F to store 1 (0x00000001)

And so on...

\$\endgroup\$
  • \$\begingroup\$ but each address such as 002AF948 is 32 bit right?. So a transition from 002AF948 to 002AF94B is 128 bits! \$\endgroup\$ – PsychedGuy Apr 1 '15 at 8:36
  • \$\begingroup\$ Why will it take a memory range of 128 bits? \$\endgroup\$ – PsychedGuy Apr 1 '15 at 8:39
  • \$\begingroup\$ @DigitalGeeK Nop. Each address stores 1 byte. So a address range 002AF948 to 002AF94B can store only 32 bits. To store 128 bits, you require 16 memory locations. So a address range 002AF948 to 002AF957 can store 128 bits. \$\endgroup\$ – nidhin Apr 1 '15 at 8:41
1
\$\begingroup\$

Four bytes are 32 bit since one byte is (normally) 8 bit.

In the past there have been some exotic exceptions to the 8 bit per byte rule but I don't think that they exist any longer.

\$\endgroup\$
  • \$\begingroup\$ What! I always taught that a byte = 8 bits. \$\endgroup\$ – PsychedGuy Apr 1 '15 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.