Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does second printf print 0

Tags:

c

pointers

output

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

I understand

 ptr2 - ptr1

gives 3 but cannot figure out why second printf prints 0.

like image 351
Ian McGrath Avatar asked Dec 28 '25 16:12

Ian McGrath


2 Answers

It's because when you substract two pointers, you get the distance between the pointer in number of elements, not in bytes.

(char*)ptr2-(char*)ptr1  // distance is 3*sizeof(char), ie 3
(int*)ptr2-(int*)ptr1  // distance is 0.75*sizeof(int), rounded to 0 

EDIT: I was wrong by saying that the cast forces the pointer to be aligned

like image 66
Benoit Blanchon Avatar answered Dec 31 '25 09:12

Benoit Blanchon


If you want to check the distance between addresses don't use (int *) or (void *), ptrdiff_t is a type able to represent the result of any valid pointer subtraction operation.

#include <stdio.h>
#include <stddef.h>

int main(void)
{
    char arr[] = "somestring";
    char *ptr1 = arr;
    char *ptr2 = ptr1 + 3;
    ptrdiff_t diff = ptr2 - ptr1;

    printf ("ptr2 - ptr1 = %td\n", diff);
    return 0;
}

EDIT: As pointed out by @chux, use "%td" character for ptrdiff_t.

like image 23
David Ranieri Avatar answered Dec 31 '25 09:12

David Ranieri