質問

I was doing a pointer exercise and I came across a doubt while experimenting the code. Why are these memory addresses in an array increasing by 4?

For example my output is

Value of var[0] = 2686720

Value of var[1] = 2686724

Value of var[2] = 2686728

Here is the code :

#include <stdio.h>
#include <conio.h>
main ()
{
  int var[3]= {10,100,200};
  int *ptr[3],i;

  for (i = 0; i < 3; i++)
  {
    ptr[i] = &var[i]; // assign the address of integer.
  }
  for (i = 0; i < 3; i++)
  {
    printf("\n\nValue of var[%d] = ",i);
    printf("%d",ptr[i]);               //var[0]=10  var[1]=100   var[2]=200
  }
  getch();
  return 0;
}
役に立ちましたか?

解決

First, var[i] is array of type int. So, each element of that array will take up the size of one int each. The size of an int is 4 bytes.

Next, you are using ptr[i] to hold the address of the elements of var array. So, the value of ptr [i] is increased by 4 for each element.

Here, for better understanding, you should use "%p" or "0x%x" format specifier with printf() when dealing with pointers.

Also, you should change the print statement

printf("\n\nValue of var[%d] = ",i);

to

printf("\n\nAddress of var[%d] = ",i);

as the former is conveying wrong message. Actually the output value is the address for var[i]. If you want to print the value of var[i] using ptr[i], you can consider using *ptr[i].

他のヒント

Each byte of memory is associated with an address. In your case each element of the array take 4 bytes in the memory and the address of that element is the address it's first byte.

So in your case the memory looks like this:

         Memory                Address

    |0|0|0|0|0|0|0|0|    <-    2686720   ( &var[0] )
    |0|0|0|0|0|0|0|0|    <-    2686721
    |0|0|0|0|0|0|0|0|    <-    2686722
    |0|0|0|0|1|0|1|0|    <-    2686723

    |0|0|0|0|0|0|0|0|    <-    2686724   ( &var[1] )
    |0|0|0|0|0|0|0|0|    <-    2686725
    |0|0|0|0|0|0|0|0|    <-    2686726
    |0|1|1|0|0|1|0|0|    <-    2686727

    |0|0|0|0|0|0|0|0|    <-    2686728   ( &var[2] )
    |0|0|0|0|0|0|0|0|    <-    2686729
    |0|0|0|0|0|0|1|1|    <-    2686730
    |1|1|1|0|1|0|0|0|    <-    2686731

Which means that by passing from an element to the next one, increases the address by sizeof(type), in this case sizeof(*ptr[i]) == sizeof(int)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top