Format '% d expects an argument of type' int, but argument 2 is of type 'int *

Every time I submit the program to hackerrank the following error occurs.

solution.c: In function โ€˜mainโ€™:
solution.c:22:14: warning: format โ€˜%dโ€™ expects argument of type โ€˜intโ€™, but argument 2 has type โ€˜int *โ€™ [-Wformat=]
 printf("%d", &sum);

      

Would it be really helpful if someone could tell me what this means?

+3


source to share


3 answers


I assume you have declared sum

how int

. Therefore, the correct call is printf

:

printf("%d", sum);

      

as a specifier %d

means that you are going to print int

, but you are passing in an address int

that is a pointer to int

or int *

.




NOTE . Do not confuse printf

with scanf

, as the second requires a pointer. So, to read a variable, sum

you have to use:

scanf("%d", &sum);

      

but for printing the correct path is without &

as above.

+8


source


If you want to print the address of the amount, you can use printf( "%p", &sum )



+3


source


Int is a primitive, primitives are data stored in memory. each chunk of data is specified in a specific block of memory, these blocks have "memory addresses" that refer to them.

If you define int i = 1

, your computer allocates an integer in memory (in a block with memory address fe 0xF00000) and sets its value to 1. When you refer to that integer as i

, you access the value stored at 0xF00000, which is 1

.

In C, you can also get a reference i

(the address of the memory in which it was allocated) which is prefixed with and (ampersand), by doing this you will get the memory address of the variable, not its value.

i === 1; // true
&i === 1; //false
&i === 0xF00000; //true

      

This memory address can be assigned to a pointer (the variable that "points" to the memory address, thus has no value of its own), so it can also be accessed directly by dereferencing it so that you can collect the value inside that block of memory. This is accomplished with*

int i = 1; //this allocates the 
int *ptr = &i; //defines a pointer that points to i address

/* now this works cause i is a primitive */
printf("%d", i);

/* this works also cause ptr is dereferenced, returning the
value from the address it points, in this case, i value */
printf("%d", *ptr);

      

In your example, you are passing a reference to printf (printf asks for a value and gets a memory address), so it doesn't work.

Hope this helps you understand C and pointers better

0


source







All Articles