K
K
Kirill Zhilyaev2018-04-09 23:01:06
C++ / C#
Kirill Zhilyaev, 2018-04-09 23:01:06

How to shift a pointer by a few bytes?

malloc'om allocated memory, but I want to shift the pointer by 1 byte. How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivanq, 2018-04-09
@kirill_782

int* a = malloc(len);
// ...
a = (int*)((char*)a + 1);

In char*, we add, back.

J
jcmvbkbc, 2018-04-10
@jcmvbkbc

malloc'om allocated memory, but I want to shift the pointer by 1 byte. How to do it?

malloc allocates memory with sufficient alignment for all built-in data types. Shifting the pointer to such memory by 1 byte will spoil this alignment. The result, depending on the platform, will be slow access to this memory, alignment errors corrected by the OS kernel, or alignment errors leading to program termination.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question