void * 赋值问题

发布于 2024-09-26 15:55:20 字数 665 浏览 10 评论 0原文

我想使用指针算术从数据包结构中获取一些字段。但是下面的代码有什么问题?
在第一种情况下,我认为如果我从数据包开头开始 4 个字节(2 个短字段),我会得到 tLow 。但它没有给出预期值。另外第二种情况我想通过从数据包开头开始 12 个字节来获取数据字段。什么我的想法有错吗?

struct packet{  
      short len;
      short field;
      int tLow;
      int tHigh;
      void *data;
}

int main()
{
    struct packet pack;
    struct packet *pck;

    pack.len=3;
    pack.field=34;
    pack.tLow=712;
    pack.tHigh = 12903;
    pack.data = "message";

    pck = &pack;
    int *timeLow = (int * )pck + 4; // i want to get tLow 
    printf("Time Low :%d\n",*time);

    char *msg = (char *)pck + 12 ;// want data 
    printf("Message :%s\n",msg);

    return 0;
}

I want to take some fields from packet struct using pointer arithmetic.But what is wrong with the code below ?
In first condition i think if i go 4 byte(2 short field) from beginning of packet i get tLow .But it does not give expected value.Additionally second case i want to get data field by going 12 byte from beginning of packet .What is wrong with my idea ?

struct packet{  
      short len;
      short field;
      int tLow;
      int tHigh;
      void *data;
}

int main()
{
    struct packet pack;
    struct packet *pck;

    pack.len=3;
    pack.field=34;
    pack.tLow=712;
    pack.tHigh = 12903;
    pack.data = "message";

    pck = &pack;
    int *timeLow = (int * )pck + 4; // i want to get tLow 
    printf("Time Low :%d\n",*time);

    char *msg = (char *)pck + 12 ;// want data 
    printf("Message :%s\n",msg);

    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

つ可否回来 2024-10-03 15:55:20

使用标准方法肯定会更好

int *timeLow = &(pck->tLow);

编译器可以在结构的任何成员之间插入填充字节。这些填充字节的规则充其量是由实现定义的......因此您必须查阅实现手册以确定在您的特定情况下如何(或是否)插入以及插入多少字节。另请注意,填充字节数可能会因使用不同选项的编译而异,或因编译器而异(计算机到计算机,...)而异。

您可以尝试使用 Coffsetof< /code>,但它并不漂亮:

size_t offset = offsetof(struct packet, tLow);
/* make sure offset is a multiple of sizeof (int*) */
int *timeLow = (int*)pck + offset / sizeof (int*);

或者,使用强制转换为 (char*) 并从其他答案复制代码来稍微不那么难看:-)

size_t offset = offsetof(struct packet, tLow);
int *timeLow = (int*)((char*)pck + offset);

哦!并且您的源代码中缺少一个分号

You definitely would be better using standard method

int *timeLow = &(pck->tLow);

Compilers are allowed to insert padding bytes between any member of a struct. The rules for these padding bytes are, at best, implementation defined ... so you must consult your implementation manual to be certain how (or if) and how many bytes are inserted in your specific case. Also note the number of padding bytes might change from compilation to compilation with different options or from compiler to compiler (computer to computer, ...)

You can try to use the C macro offsetof, but it's not pretty:

size_t offset = offsetof(struct packet, tLow);
/* make sure offset is a multiple of sizeof (int*) */
int *timeLow = (int*)pck + offset / sizeof (int*);

or, a little less ugly using a cast to (char*) and copying the code from other answers :-)

size_t offset = offsetof(struct packet, tLow);
int *timeLow = (int*)((char*)pck + offset);

Oh! and there's a semi-colon missing in your source

不寐倦长更 2024-10-03 15:55:20

基本上你依赖于未定义的行为。结构对齐等。但无论如何...

(int*)pck + 4。将使指针前进4 * sizeof(int)。这是错误的,如果我们假设结构体已打包并且 sizeof(short) == 2,我们希望将其前进 1,从而...

int *timeLow = (int * )pck + 1; // i want to get tLow 
printf("Time Low :%d\n",*timeLow);

打印正确的结果。

至于消息,你需要做一些肮脏的事情。由于我使用的是 x86_64,编译器选择在 8 字节边界上填充 void*,因此偏移量为 16,而不是预期的 12。

我们基本上是在获取指向 void* 的指针。所以代码将如下所示:

char **msg = (char**)((char *)pck + 16) ;// want data 
printf("Message :%s\n",*msg);

永远编写这样的代码,这只是说明了一点。

Basically you are relying on undefined behavior. Struct alignment, etc. But anyways...

(int*)pck + 4. Will advance the pointer 4 * sizeof(int). This is wrong, we want to advance it by 1 if we assume that the struct is packed and sizeof(short) == 2, thus...

int *timeLow = (int * )pck + 1; // i want to get tLow 
printf("Time Low :%d\n",*timeLow);

prints the correct result.

As for the message, you need to do some dirty stuff. Since I'm on x86_64 the compiler chose to pad the void* on 8 byte boundaries, so the offset was 16 rather than the expected 12.

We're basically fetching a pointer to a void*. So the code will look like this:

char **msg = (char**)((char *)pck + 16) ;// want data 
printf("Message :%s\n",*msg);

NEVER write code like this, this just illustrates a point.

筱武穆 2024-10-03 15:55:20

您正在寻找offsetof

您的代码可能如下所示:

int *timeLow = (int*) ((char*)pck + offsetof(struct packet, tLow);

正如 pmg 指出的那样,

int *timeLow = &(pck->tLow);

这是获取指向结构成员的指针的规范方法。

这个答案还带来了指针算术 - 感谢 pmg,我今天学到了这一点。

You are looking for offsetof.

Your code could look like this:

int *timeLow = (int*) ((char*)pck + offsetof(struct packet, tLow);

and as pmg pointed out,

int *timeLow = &(pck->tLow);

is the canonical way of getting a pointer to a member of a struct.

This answer also brought pointer arithmetics on the table - which I learned today thanks to pmg.

星光不落少年眉 2024-10-03 15:55:20

当您编写时,

int *timeLow = (int * )pck + 4

您将“pck”视为 int 指针,根据您的系统,该指针可能是 4 或 8 个字节。
这不会正确地偏移到结构中,因为你告诉它有一个 4 int 的偏移量,

而不是你需要这样做

int *timeLow = (int*)((short * )pck + 2); 

when you write

int *timeLow = (int * )pck + 4

you are treating 'pck' as a int pointer which depending on your system may be 4 or 8 bytes.
That will not correctly offset into the struct because you are then telling it to have an offset of 4 int

instead you would need to do like this

int *timeLow = (int*)((short * )pck + 2); 
我做我的改变 2024-10-03 15:55:20

Short 不一定是 2 个字节长。所指定的只是它们小于或等于整数的大小。您可能应该使用 sizeof()

Shorts are not necessarily 2 bytes long. All that is specified is that they are less-than or equal-to the size of ints. You should probably be using sizeof()

幼儿园老大 2024-10-03 15:55:20

这是错误的:pack.data = "message";
您正在使用未分配的内存。

还有这个:int *timeLow = (int *)pck + 4;
不保证工作(结构对齐因编译器和系统而异)。

This is wrong: pack.data = "message";
You are using unallocated memory.

Also this: int *timeLow = (int * )pck + 4;
is not guaranteed to work (struct alignment varies between compilers and systems).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文