简体   繁体   中英

Getting negative address in c

#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

  1. %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.

  2. In this code, *p does not denote an address, anyway.

  3. You cannot print an array by just using the %d s 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 int s 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);

For pointers, use %p with printf() :

int a[5] = {0, 1, 2, 3, 4}, *p;
p = a;
printf("%p\n%d", (void *)p, *p);

Also make sure your comiler warnings are at the highest level. You should get a warning for using %d with a pointer then:

warning <code>: 'printf'  : '%d' in format string conflicts with argument 1 of type 'int *'

Mis-matched printf() specifiers and arguments

printf("%d\\n%d\\n%d\\n%d\\n%d\\n", p, *p); expects 5 int . Code is supplying a int * and int . Result: undefined behavior.

Instead:

printf("Pointer %p\nValue: %d\n", (void *) p, *p);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM