【问题标题】:Why we can get offset of a struct like this?为什么我们可以得到这样的结构的偏移量?
【发布时间】:2015-03-06 09:14:53
【问题描述】:

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

#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

【问题讨论】:

  • 使用哪些编译器标志以及您正在构建该程序的编译器?
  • 不,错误:在 ':' 标记 codepad.org/ZsNJY08g 之前需要 ')'
  • gcc -g -O2 -Wall -o main.o main.cpp
  • 对不起,我在文本中更新了整个程序和编译器标志
  • 在我的电脑上编译不了,::C++神器,使用printf("%zu\n", offsetof(struct sdshdr, len));

标签: c struct offset


【解决方案1】:

您展示的代码不是 C 兼容代码。这些结构

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

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

如果您想知道 C 中结构的数据成员的偏移量,那么您应该使用标头 &lt;stddef.h&gt; 中声明的标准宏 offsetof

例如

#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::lenand&sdshdr::free` 表示指向结构中数据成员的指针。

【讨论】:

  • It seems you compiled the code as a C++ code.,编译参数:gcc ...,编译为你需要的 C++ 代码g++ ...,不是吗?
  • @Alter Mann 我自己使用 MS VC++。 :) 但是我看到程序的扩展名是.cpp:main.cpp。所以我确信代码被编译为 C++ 代码。
  • 糟糕,将扩展名从 .c 更改为 .cpp 并且编译时出现警告,我不知道
  • @Alter: gcc 将从扩展中推断语言;在这种情况下,它假定 *.cpp 是一个 C++ 文件,除非您明确告知它。 (至少我假设它从 *.cpp 推断出 C++。我知道它会从 *.cc 推断出来)
  • @Alter Mann 这是我在 stackoverflow 上的第一个问题,似乎我不清楚的描述给你带来了麻烦,对此感到抱歉。下次会更加小心。
猜你喜欢
  • 1970-01-01
  • 2018-12-13
  • 2020-04-12
  • 2019-06-23
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多