0

I'm trying to understand the concept of pointers. So I wrote a code (from a book I have) but It doesn't complile. Can't understand what is wrong, again I wrote exactly how it is in the book, and I checked if there are some mistakes, but I can't find any...

Here is the code:

#include <stdio.h>

int var = 1;
int *ptr;
 
int main(void)
{
    ptr = &var;   
     
    printf("Var = %d", var);
    printf("Var = %d", *ptr);
    
    printf("The adress of the variable = %d", &var);
    printf("The adress = %d", ptr);

    return 0;
}

Here are the errors I got:

ø.c:13:47: error: format specifies type 'int' but the argument has
type 'int *' [-Werror,-Wformat]
    printf("The adress of the variable = %d", &var);
                                         ~~   ^~~~ ø.c:14:31: error: format specifies type 'int' but the argument has type 'int *'
[-Werror,-Wformat]
    printf("The adress = %d", ptr);
                         ~~   ^~~
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115

2 Answers2

3

Use "%p" for pointer (not "%d").

fana
  • 1,370
  • 2
  • 7
  • You might add that the pointer value must be cast to `(void*)` – Gerhardh Oct 28 '22 at 09:32
  • I don't think the cast is really required here. Because, I think that the function `printf` is just interpreting the arguments as specified. (So I'm surprised that the compiler does such a kind check.) Is this my thinking wrong for C specification? – fana Oct 28 '22 at 09:55
  • 1
    `printf` expects to get a `void*`. Due to missing parameter list, the compiler cannot do automatic conversion. You must do it explicitely. – Gerhardh Oct 28 '22 at 10:02
  • Thanks. Now, I understand the problem is as "when void* and other pointer types (such as int*) do not become the same bit pattern, ...". – fana Oct 29 '22 at 01:33
-1
 #include <stdio.h>

 int main(void)
 {
     int var = 1;
     int *ptr;
     ptr = &var;   
 
     printf("Var = %d", var);
     printf("Var = %d", *ptr);

     printf("The adress of the variable = %p", &var);
     printf("The adress = %p", ptr);

     return 0;
 }  
JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • 2
    Code without any explanation are considered poor answers. Also in an answer code should be properly indented, – Jabberwocky Oct 28 '22 at 09:27