1

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
sobha
  • 165
  • 1
  • 9

1 Answers1

7

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

Use %td to print the result.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261