Printing the variables address using pointers in c++

Discussion in 'Programmer's Corner' started by asilvester635, Feb 7, 2017.

  1. asilvester635

    Thread Starter Member

    Jan 26, 2017
    Why won't it print the address???

    Code (Text):
    2. int a = 10;
    3.     int* p;
    4.     p = &a;
    5.     int size = sizeof(int);
    6.     printf("Address of p is %d\n", p);
    7.     printf("Size of integer is %d\n", size);
    8.     printf("Address p+1 is \n", p+1);
    The error it's giving me is below
    g++ -c -Werror error: format specifies type 'int' but the argument has type

    'int *' [-Werror,-Wformat]

    printf("Address of p is %d\n", p);

    ~~ ^ error: data argument not used by format string


    printf("Address p+1 is \n", p+1);

    ~~~~~~~~~~~~~~~~~~~ ^

    2 errors generated.

    make: *** [main.o] Error 1
  2. Papabravo


    Feb 24, 2006
    Because the types are not interchangeable. The format specifier in the the printf function call (%d), requires an integer. The type of the argument is pointer to integer. You used to be able to get away with this false equivalence, but I'm guessing that the compiler is calling you out for your ham-handed attempt to bypass strong type checking. Do you know what a typecast is?

    In the second case the format specifier string has do description of the type for p+1. It just contains characters that are printed literally.

    You might want to go back an restudy the first principles of such things because it seems they went right over your head on first reading. Also it might be worthwhile for you to study the library code for printf. It was one of the first things I did when I learned the C-language in 1978. Although the compiler might be C++, you are using any C++ syntax or semantics yet.
  3. WBahn


    Mar 31, 2012
    Also, on many modern compilers, a pointer is an 8-byte unsigned integer, not a 4-byte unsigned integer. So I would recommend casting your pointer to an 8-byte unsigned integer (which may be a long or may be a long long) and then using the corresponding format specifier.