指向数组定义明确行为的 C 指针

标签 c

C 标准是否很好地定义了此函数的返回值?

int foo()
{
    char buff[128];
    // This is the important line:
    if ((void*)buff == (void*)(&buff))
        return 1;
    else
        return 0;
}

foo 的结果是什么?在 gccclang 上,它将始终为 1但我不认为这是由标准保证的.

最佳答案

Are they [buff and &buff] guaranteed to have the same value or is that something that just happens with gcc and clang? I ask because I don't think &buff is "the address of the start of the array," but the address of the variable buff.

它们保证是相同的值。在 C 语言中,数组可以被认为是“特殊的”,因为它们不是指针,唯一一次被如此对待是当它们被传递给一个函数并且它们退化为指针时。

出于这个原因:

buff == &buff && buff == &buff[0]

不过 buff&buff 是两种不同的类型,其中 &buff 是指向数组的指针(它们仍然指向同一个点!)。您可以对两者使用 sizeof 来亲眼看到这种差异。

这对于指针来说是一样的,正如您所说,它将返回该实际指针变量的地址。数组也不是指向自身的指针,因为为了使指针指向自身,该指针的地址需要存储在该指针变量中。

数组名只是编译器使用的一个标签,它对应于一个连续的内存块。它具有特殊的属性,上述是其中之一。

关于指向数组定义明确行为的 C 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8423284/

相关文章:

内核非对称加密中的 crypto_akcipher_set_pub_key 始终返回错误

arrays - 如何将指针/数组作为参数传递给 GTK 回调函数?

c - 避免暴露已编译 C 模块的详细信息

c - 二维数组传递

c - 在 Visual Studio 2008 Professional 中使用 timeGetTime() 时出现问题

无法在字符数组中 scanf '-' 或 '+'

C - 使用 libcurl 列出 imap 发送的邮件

c - 使用 CMake 测试 GSL 时 CBLAS 中 undefined reference

c - 基数右边的分数 - float 转换

c - 将打印哪个值?