c - 为什么我们可以获得这样的结构的偏移量?

标签 c struct offset

今天得到一些信息,我们可以通过这种方式获取结构中字段的偏移量:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

struct sdshdr {
    int len;
    int free;
};

int main(int argc, char* argv[])
{
    printf("%d\n", &sdshdr::len);
    printf("%d\n", &sdshdr::free);
}

虽然编译的时候有警告,但是可以成功运行。 我们该如何解释呢?我在网上搜索时没有得到信息。 谁能帮忙解释一下这里发生了什么?

编译参数:gcc -g -O2 -Wall -o main.o main.cpp

最佳答案

您显示的代码不是 C 兼容代码。这些建筑

&sdshdr::len&sdshdr::free不是有效的 C 结构。

您似乎将代码编译为 C++ 代码。

如果您想知道 C 中结构的数据成员的偏移量,那么您应该使用标准宏 offsetof在 header 中声明 <stddef.h>

例如

#include <stdio.h>
#include <stddef.h>

struct sdshdr {
    int len;
    int free;
};


int main(void) 
{
    printf( "offset of len is equal to %zu\n", offsetof( struct sdshdr, len ) );    
    printf( "offset of free is equal to %zu\n", offsetof( struct sdshdr, free ) );  

    return 0;
}

程序输出可能是这样的

offset of len is equal to 0
offset of free is equal to 4

如果你指的是 C++,那么这些表达式

&sdshdr::len and &sdshdr::free` 表示指向结构内数据成员的指针。

关于c - 为什么我们可以获得这样的结构的偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28895556/

相关文章:

c - 尝试将字符串扫描到c中结构的2个不同元素

javascript offsetTop 属性既成功又同时出现错误

c - 在 C shell 中实现管道 (Unix)

c - 如果我说 calloc(1000, 23),那么 23 "round up"会变成 24 吗?还是到32?

c - 使用 C 访问数组的连续部分

c - 初始化结构体的成员

c - 将指针与(无符号)-4000L 进行比较的目的

c++ - 在 C++ 中将结构复制到数组中

javascript - 如何获取固定元素的 "original"offset().top ?

ios - UIScrollView contentOffset 在切换到前台时自动设置