Search code examples
cpointerssubtraction

Why trying to print the result of subtraction of two pointers throwing warning?


I am trying to subtract 2 pointers such that they such give the number of elements.I could compile the program and run it .But after compilation it is throwing error as

pointerarithmetic.c: In function ‘main’:
pointerarithmetic.c:9:8: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
 printf("%d",(q-p));

The code:

#include<stdio.h>

    int main(){
    int a[5]={0,10,20,30,40};
    int *p,*q;
    p=&a[0];
    q=&a[2];
    printf("%d",*p);
    printf("%d",*q);
    printf("%d",(q-p));
    return 0;
    }

The expected output should be number of elements.


Solution

  • Subtraction of pointers return a type ptrdiff_t (defined in stddef.h), not an int.

    Use %td to print the result.