Each time I submit a program on hackerrank the following error occurs.
solution.c: In function ‘main’:
solution.c:22:14: warning: format ‘%d’ expects argume
If you want to print the address of sum you can use printf( "%p", &sum )
I assume that you have declared sum
as an int
. So the correct call to printf
is :
printf("%d", sum);
as %d
specifier means that you are going to print an int
, but you are passing the int
's address, which is a pointer to int
, or int *
.
NOTE : Do not confuse printf
with scanf
, as the second does require a pointer. So, for reading variable sum
, you would use :
scanf("%d", &sum);
but for printing, the correct way is without &
, as written above.
Int is a primitive, primitives are data stored in memory. each data chunck is set in a specific memory block, those blocks has "memory addresses" that refer to them.
If you define int i = 1
your computer allocates an integer in memory (in a block, with a memory address f.e. 0xF00000) and sets its value to 1.
When you refer to this integer as i
, you are accessing the value stored in 0xF00000, that happen to be 1
.
In C you can also get the i
reference (the memory address it's allocated in) by prefixing it with & (ampersand), by doing this you will get the memory address of the variable rather than its value.
i === 1; // true
&i === 1; //false
&i === 0xF00000; //true
This memory address can be assigned to a pointer (a variable that 'points' to a memory address, thus, have no it's own value) so it can be accessed directly too dereferencing it so you can gather the value inside that memory block. This is achieved using *
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's value */
printf("%d", *ptr);
In your example, you are passing a reference to printf (printf asks for a value and is receiving a memory address) so it doesnt work.
Hope this helps you understand C and pointers better