0

I was trying to print the address of a variable using printf and cout in my .cpp file but both the line gives me different output.

Here is the code

#include <bits/stdc++.h>
using namespace std ;

int main(){
    int a = 5 ;
    cout << &a << endl ;
    printf("%u\n",&a);
}

if the variable is same how can the address be different?

Evg
  • 25,259
  • 5
  • 41
  • 83
  • 3
    Who teaches `#include `? Throw away that piece of nonsense. [Why should I not `#include `?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Evg Feb 18 '23 at 18:20
  • *how can the address be different?* - Why do you think they are different? – Evg Feb 18 '23 at 18:22
  • 1
    `printf("%u\n",&a);` should be `printf("%p\n", (void *)&a);`. Your `%u` is for type `unsigned int`. – Weather Vane Feb 18 '23 at 18:23
  • but why should we include (void *) – Ritik Singh Feb 18 '23 at 19:10
  • @RitikSingh: `(void *)` is a [type cast](https://en.cppreference.com/w/cpp/language/explicit_cast). According to the C and C++ standard, the `%p` `printf` conversion format specifier requires a `void *` argument, not just any pointer argument. The standards do not require the size or representation of a `void *` to be the same as pointers to other types, but all pointer types (except function pointers) must be convertable to `void *`. However, on most modern platforms, they do have the same size and representation, so the cast to `void *` when using `%p` is not necessary on those platforms. – Andreas Wenzel Feb 18 '23 at 20:47

0 Answers0