How to make a pointer increment by 1 byte, not 1 unit
Asked Answered
A

2

16

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?

Amity answered 16/5, 2013 at 2:28 Comment(3)
That's probably the only solution.Seely
You really don't want to do that...or, perhaps, why on earth do you think you want to do that (because you really don't want to do that!)?Snowfield
No, that's exactly the right way to do it. But why would you want to?Wayless
E
17

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

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

opt = (tcp_option_t *) ptr;
Elbertelberta answered 16/5, 2013 at 3:51 Comment(1)
That won't work at all if ptr has been incremented by less than sizeof tcp_option_t .Menagerie
M
-1

I know this post is very old, but I had the same question and found this solution:

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

No need to restore the struct.

This is working on Visual Studio 2005. I hope it works with all compiler.

Metaphysics answered 27/11, 2023 at 8:49 Comment(1)
Sorry, but what does this answer add to the already given one (except unnecessary asterisks and confusion?)Pantelleria

© 2022 - 2024 — McMap. All rights reserved.