C - Pointer + 1 Meaning

18,351

Solution 1

Ah, yes, that old chestnut. There's a bit of magic going on when you add N to a pointer; the compiler intuits that you want the address of the Nth item, and multiplies the offset by the size of the datatype.

Solution 2

This is because int is 4 bytes on this system. So +1 on a pointer will increment it by 4 instead of just 1.

When you increment a pointer, you increment it by it's actual size and not the pointer value itself.

Solution 3

pointer + j is the same as &(pointer[j]), so its the adress of the j:th element in the array pointed to by pointer. Obviously, a pointer to a large data type will be incremented more than a pointer to a small data type.

Share:
18,351
kazinix
Author by

kazinix

Updated on July 12, 2022

Comments

  • kazinix
    kazinix almost 2 years

    What the codes basically do is to print the address of each element in the int and char arrays pointed to by pointers i and ch.

    #include<stdio.h>
    
    int main()
    {
        char *ch;
        int *i;
        int ctr;
    
        ch = malloc(sizeof(char)*10);
        i = malloc(sizeof(int)*10);
    
        printf("Index\ti Address\tch Address\n\n");
    
        for(ctr=0; ctr<10; ctr++)
        {
            printf("%d\t%p\t%p\n",ctr,i+ctr,ch+ctr);
        }
    
        getch(); 
        return  0;
    }
    

    Result:

    Index   i Address       ch Address
    
    0       00511068        00511050
    1       0051106C        00511051
    2       00511070        00511052
    3       00511074        00511053
    4       00511078        00511054
    5       0051107C        00511055
    6       00511080        00511056
    7       00511084        00511057
    8       00511088        00511058
    9       0051108C        00511059 
    

    I understand that each element in two arrays occupies space size of their data type. My problem is, I'm confused to this operation:

    i+1
    

    If i is 00511068 , then i+1 is 00511069 as opposed to the result. What does i+1 means? How do you read it? I think I don't fully understand pointer. Please help me understand it. Thank you.