Fairly easy pointer increment program is as follows.


int main(){
    int i,a[10],*p=a;
    for (i=0; i<10; i++,p++){
        printf("\nAddress of a[%d] is %d",i,p);
    return 0;

Here is output:

Address of a[0] is 2293488
Address of a[1] is 2293492
Address of a[2] is 2293496
Address of a[3] is 2293500
Address of a[4] is 2293504
Address of a[5] is 2293508
Address of a[6] is 2293512
Address of a[7] is 2293516
Address of a[8] is 2293520
Address of a[9] is 2293524

It's suppose to increment address by 2 Bytes, but actually its incrementing to 4 Bytes. Did standard size for Integer changed to 4 Bytes ? OR Am I missing something ?

you can easily find out the size of an int by printing sizeof(int) -- but to answer your question, on most 32-bit compilers sizeof(int) == 4. If you are accustomed to using Turbo C, that is a 16-bit compiler and sizeof(int) == sizeof(short) == 2. But on most modern compilers sizeof(int) is not the same as sizeof(short). It's never a good idea to outguess the size of integers becaue it can vary from one compiler to another, and the C standards make no such assumption.

printf("sizeof(short) = %d\n", sizeof(short));
printf("sizeof(int) = %d\n", sizeof(int));
printf("sizeof(long) = %d\n", sizeof(long));
printf("sizeof(long long) = %d\n", sizeof(long long));

Edited 2 Years Ago by Ancient Dragon

Integer has nothing to do with pointer size. The pointer is the size of the memory address as dictated by the Operating System based on the CPU's capabilities. A 32 bit CPU will have a 4 byte address whereas a 64 bit CPU will have an 8 byte address. Some Operating Systems will have an emulation layer that would change this address size.

Be careful assuming the size of the pointer as you will force your software to be locked into specific system specifications. Use this line of code when you need to figure that sort of thing out:

int PointerSizeOnThisSystem = sizeof(char *);

Although what you said is correct, the question was why did the pointer increment by 2 instead of 4, which is not the same as the answer you provided. I think you misunderstood the question. In the question, the number of bytes by which the pointer is incremented is the sizeof one element of the array.

I just tested the code and it agrees with Ancient Dragon's explanation. Sorry about that.

Edited 2 Years Ago by N1GHTS

When p is an integer pointer then p++ incrments by sizeof(int), not by sizeof(int *), and the code he posted proves it. Had p been a pointer to an array of char, then p++ would have incremented by sizeof(char), or 1.

Edited 2 Years Ago by Ancient Dragon

This question has already been answered. Start a new discussion instead.