Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Pointer + 1 Meaning

Tags:

arrays

c

pointers

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.

like image 310
dpp Avatar asked Nov 27 '22 14:11

dpp


2 Answers

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.

like image 105
Phil Lello Avatar answered Dec 18 '22 08:12

Phil Lello


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.

like image 41
Mysticial Avatar answered Dec 18 '22 09:12

Mysticial