1

I have a C array as follows:

 unsigned long arr[10];

On my machine, unsigned long is 8 bytes. I have a situation where I write 4 bytes using arr[0], and then need to find the address of the next byte in the array.

 void * ptr = arr[0] + (sizeof(unsigned long) / 2);

Will the above work ?

4
  • 1
    it will work on your machine, but is undefined behavior/won't work on other systems. Sizes of types are implementation dependant in c. Commented Apr 26, 2015 at 22:43
  • Are you trying to always advance the pointer by 4 bytes, or are you trying to always advance by half the size of an unsigned long? Commented Apr 26, 2015 at 22:53
  • By half the size of unsigned long Commented Apr 26, 2015 at 22:58
  • @Jake, Then the answer I wrote should do what you want. Commented Apr 26, 2015 at 22:58

1 Answer 1

6

No it will not. You should cast to char* first and then do the pointer arithmetic.

 void * ptr = ((char*) &arr[0]) + (sizeof(unsigned long) / 2);
Sign up to request clarification or add additional context in comments.

1 Comment

It seems like the OP wants to advance by half the size of an unsigned long. You should do sizeof(unsigned long) / 2 to account for cases where sizeof(unsigned long) is not 8 bytes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.