如何通过1个字节,而不是1单元以使一个指针增量 [英] How to make a pointer increment by 1 byte, not 1 unit

查看:119
本文介绍了如何通过1个字节,而不是1单元以使一个指针增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构 tcp_option_t ,这是 N 字节。如果我有一个指针 tcp_option_t *选择,我希望它由1递增,我不能使用选择++ ++选择,因为这将递增的sizeof(tcp_option_t),这是ñ

I have a structure tcp_option_t, which is N bytes. If I have a pointer tcp_option_t* opt, and I want it to be incremented by 1, I can't use opt++ or ++opt as this will increment by sizeof(tcp_option_t), which is N.

我想只有一个字节来移动这个指针。我目前的解决方案是

I want to move this pointer by 1 byte only. My current solution is

opt = (tcp_option_t *)((char*)opt+1);

但它是一个有点麻烦。是否有更好的办法?

but it is a bit troublesome. Are there any better ways?

推荐答案

我建议你创建的char指针,并用它来横向你的结构。

I'd suggest you to create a pointer of char and use it to transverse your struct.

char *ptr = (char*) opt;
++ptr; // will increment by one byte

当您需要重新恢复你的结构,从PTR,只是做一般的转换:

when you need to restore your struct again, from ptr, just do the usual cast:

opt = (tcp_option_t *) ptr;

这篇关于如何通过1个字节,而不是1单元以使一个指针增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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