I wrote this program which displays the address of a stored array :
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int L[100];
for (int i = 0; i < n; i ) {
printf("L[%d]=", i);
scanf("%d", &L[i]);
}
printf("The address of L : %d \n", L);
return 0;
}
I noticed that sometimes the program gives negative address which I did not quite understand.
Why there are negative addresses in memory?
Is this related to the C language?
CodePudding user response:
Why there are negative addresses in memory?
This is an unsupported concern as the output was based on broken code.
Do not use a mis-matched specifier "%d"
to print addresses and incur undefined behavior (UB). "%d"
is for int
. Use "%p"
with void *
. The format of address output is implementation dependent. I have never come across an implementation that reports negative addresses.
printf("The address of L : %p\n", (void *) L);
You may get an output like
The address of L : 0xffffca70
// or
The address of L : ffff:ca70
// or
The address of L : Red:70
A pointer has integer like attributes, but a pointer type is not certainly reported like an integer. It is implementation defined.
Save time - enable all warnings too.