offsetof [英] offsetof

查看:79
本文介绍了offsetof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,


我的实现没有定义offsetof,所以我设计了一个小的

程序,试图找到相对位置

结构中的成员。它只是不起作用。


我可以得到一些关于我做错的指示(除了编码

如此深夜)。 />

#include< stdlib.h>

#include< stdio.h>


int main(void )

{

struct new

{

int a;

char b ;

char c;

} x;


size_t num;


num =(size_t)((struct new *)& xc - & x);


printf("%u\\\
",num);


返回EXIT_SUCCESS;

}


总是返回0.


谢谢。


-


Alejo

Hello,

My implementation does not define offsetof, so I have designed a little
program that ''attempts'' to find the relative position of a member in its
structure. It just does not work.

Could I get some pointers on what I am doing wrong (apart from being coding
so late at night).

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

int main( void )
{
struct new
{
int a;
char b;
char c;
} x;

size_t num;

num = (size_t)((struct new *)&x.c - &x);

printf( "%u\n", num );

return EXIT_SUCCESS;
}

It always returns 0.

Thanks.

--

Alejo

推荐答案

Alejo写道:
你好,

我的实现没有定义offsetof,所以我设计了一个小小的
程序,试图找到找到相对位置
结构中的成员。它只是不起作用。

我可以得到一些指示我做错了什么(除了编码如此深夜)。

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

int main(无效)
{
struct new
{
int a;
char b;
char c;
} x;

size_t num;

num =(size_t)( (struct new *)& xc - & x);

printf("%u \ n",num);

返回EXIT_SUCCESS;
}

它总是返回0.
Hello,

My implementation does not define offsetof, so I have designed a little
program that ''attempts'' to find the relative position of a member in its
structure. It just does not work.

Could I get some pointers on what I am doing wrong (apart from being coding
so late at night).

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

int main( void )
{
struct new
{
int a;
char b;
char c;
} x;

size_t num;

num = (size_t)((struct new *)&x.c - &x);

printf( "%u\n", num );

return EXIT_SUCCESS;
}

It always returns 0.




把它放在一边。你为什么要这样做呢?

成员的偏移量不是非常便携的数量。因此,如果这已经与

加载/保存到文件[或内存缓冲区],你应该重新考虑你的

设计。


对于一般问题,也许.c是第一个由编译器打包的元素。尝试执行


x.c = 4;


并获取编译器生成的汇编代码。我的编译器[gcc

3.3.1预发布]产生


main:

pushl%ebp

movl%esp,%ebp

subl



Leave that aside. Why are you doing this anyways? The offset of
members is not a terribly portable quantity. So if this has todo with
loading/saving to a file [or memory buffer] you ought to rethink your
design.

As to the general question, maybe .c is the first element as packed by
the compiler. Try doing

x.c = 4;

and get the assembler code the compiler produces. My compiler [gcc
3.3.1 pre-release] produces

main:
pushl %ebp
movl %esp, %ebp
subl


8,%esp

andl
8, %esp
andl


-16,%esp

movb
-16, %esp
movb


这篇关于offsetof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆