-1

I wrote a program to understand a concept of pointer, where i declared an array of 5 integer pointers and then i tried to print the address of various indices of the array. But what I do not understand is that why is the difference between the consecutive address of indices of 8 bits and not of 4 bits in the output?

My code is:

#include<stdio.h>
void main()
{
    int i;
    int *b[5];

    for(i = 0; i < 5; i++){
        b[i] = (int *) malloc(10 * (sizeof(int)));}
    printf(" b = %u \n\n",b);
    printf(" (b+1) = %u \n\n", (b+1));
    printf(" (b+2) = %u \n\n", (b+2));
    printf(" *(b+2) = %u \n\n", *(b+2));
    printf(" *(b+2)+3) = %u \n\n", *(b+2) + 3);
    *(*(b+2) + 3) = 5;
    printf(" b[2][3] = %u \n\n", b[2][3]);
}

The output is as follows

b = 79107440 

 (b+1) = 79107448 

 (b+2) = 79107456 

 *(b+2) = 3293532864 

 *(b+2)+3) = 3293532876 

 b[2][3] = 3293533008 

Clearly the difference between (b+1) and b is of 8 bits.WHY?

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
S.Sharma
  • 23
  • 5

3 Answers3

3

First of all, the addresses are in bytes, not bits. Second as to why the difference is 8 bytes, it is because you are on a system that uses 64 bit (8 byte) addresses.

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
2

int *b[5] is an array of pointers on int so the difference between b and b + 1 is equal to sizeof(int*) witch is 8 bytes on you pc

Tyker
  • 2,971
  • 9
  • 21
2

First of all, you might use %p to show your pointer's address, not %u. In fact, %d is a signed integer, while %u is an unsigned integer and %p a pointer.

Concerning the answer, on your machine, int is apparently 4 bytes but pointers are 8 bytes (typical 64 bit machine).

Adam Perea
  • 320
  • 2
  • 9
  • This should be a comment, not an answer, unless the last sentence is intended to answer the question. If so, the answer should be reworded so that is clear and is first. – Eric Postpischil Jun 21 '18 at 11:38