#include <stdio.h>
int main(void) {
int a[5] = {0, 1, 2, 3, 4}, *p;
p = a;
printf("%d\n%d\n%d\n%d\n%d\n", p, *p);
return 0;
}
When I executed this code, I got a negative value for p. I have studied that address cannot be negative. Then why I have got a negative value
%d is not the correct format specifier to handle a pointer (address). You should be using %p and cast the corresponding argument to void* for printing an address. Using wrong argument type for a particular format specifier invokes undefined behavior.
To quote C11 chapter §7.21.6.1
[...] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
In this code, *p does not denote an address, anyway.
You cannot print an array by just using the %ds in a single format string. You need to have a loop. In your code,
printf("%d\n%d\n%d\n%d\n%d\n", p, *p);
the format string expects 5 ints as argument, while you supply only a pointer and an int. FWIW, supplying insufficient argument for supplied conversion specifiers invoke undefined behavior, too. Quoting the same standard,
[...] If there are insufficient arguments for the format, the behavior is undefined. [...]
To elaborate, replace
printf("%d\n%d\n%d\n%d\n%d\n", p, *p);
by
for (i= 0; i < 5; i++, p++)
printf("%d %p\n", *p, (void *)p);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With