为什么数组的地址可以有负值?

The*_*ing 1 c memory arrays memory-management

我编写了这个程序,它显示存储数组的地址:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我注意到有时程序给出了我不太理解的负地址。

为什么内存中有负地址?
这和C语言有关系吗?

chu*_*ica 7

为什么内存中有负地址?

这是一个不受支持的问题,因为输出是基于损坏的代码。


不要使用不匹配的说明符"%d"来打印地址并导致未定义的行为(UB)。 "%d"是为了int. "%p"与 一起使用void *。地址输出的格式取决于实现。我从未遇到过报告负地址的实现。

printf("The address of L : %p\n", (void *) L);
Run Code Online (Sandbox Code Playgroud)

您可能会得到类似的输出

The address of L : 0xffffca70
// or 
The address of L : ffff:ca70
// or 
The address of L : Red:70
Run Code Online (Sandbox Code Playgroud)

指针具有类似整数的属性,但指针类型不一定像整数一样报告。它是实现定义的。


节省时间 - 也启用所有警告。

  • @AndrejsCainikovs“如果转换规范无效,则行为未定义。” C17dr § 7.21.6.1 9. (4认同)
  • @dai Re:“关于鼻恶魔的事情” --&gt; 如果你的鼻子/代码流鼻涕,你可能会认为这很有趣,但它是鼻涕。;-)。 (2认同)