Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the output of this program comes out to be this?

Tags:

c

I have a piece of code written in C where some pointer arithmetic is performed. I would like to know how the output comes to be this?

#include <stdio.h>  
int main()
{
    char arr[] = "gookmforgookm";
    char *ptr1 = arr;
    char *ptr2 = ptr1 + 3;
    printf ("ptr2 - ptr1 = %d\n", ptr2 - ptr1);
    printf ("(int*)ptr2 - (int*) ptr1 = %d",  (int*)ptr2 - (int*)ptr1);
    getchar();
    return 0;
}

Output is below:

ptr2 - ptr1 = 3  
(int*)ptr2 - (int*) ptr1 = 0
like image 226
Amit Singh Tomar Avatar asked Dec 14 '11 07:12

Amit Singh Tomar


Video Answer


3 Answers

Strictly speaking, you're invoking undefined behaviour and any result that the program produces is OK according to the C standard.

However, you're probably on a machine where sizeof(int) == 4 (as opposed to say, 2). Since there are 4 bytes to an integer, two addresses which are 3 bytes apart are part of the same integer, so the difference between the addresses is 0 * sizeof(int). You might find a different answer if you chose ptr1 = arr + 1;, or you might not. But that's the beauty of undefined behaviour - it would be 'right' either way.

like image 193
Jonathan Leffler Avatar answered Sep 29 '22 09:09

Jonathan Leffler


After the subtraction you need to divide the result in the size of the pointed type.

(int*)ptr2 - (int*)ptr1 == (0x1000003 - 0x1000000) / sizeof(int)
(int*)ptr2 - (int*)ptr1 == (0x1000003 - 0x1000000) / 4 == 0
like image 40
MByD Avatar answered Sep 29 '22 09:09

MByD


ptr1 and ptr2 are both char * type, that means one byte one pointer.

char *ptr2 = ptr1 + 3;

so

ptr2 - ptr1 = 3

Next, you cast both pointer to type int *, int type need 4 byte, so both pointer aim at the same int, both pointer have the same value through the memory align, you get the 0 result.

like image 41
Louis Avatar answered Sep 29 '22 08:09

Louis