I'm using this code to move pointer by 1 byte now, but I'm feeling something unclear..
int* a = (int*)malloc(sizeof(int));
void* b = ((char*)a)+1;
char
is 1 byte, but not defined for byte operation purpose. I believe there's another way to do this byte operation. What's the correct way to byte operation?
PS. I modified sample code to be valid. It's now compiled as C++ with Clang.
Unlike regular numbers, adding 1 to a pointer will increment its value (a memory address) by the size of its underlying data type.
You can only add or subtract integers to pointers. When you add (or subtract) an integer (say n) to a pointer, you are not actually adding (or subtracting) n bytes to the pointer value. You are actually adding (or subtracting) n-times the size of the data type of the variable being pointed bytes.
Incrementing an int pointer will increase its value by four because the next valid integer address is four bytes from the current location. A programmer can simply write ptr++ to make a pointer point to the next element value.
Size of Character Pointer Output: The size of the character pointer is 8 bytes. Note: This code is executed on a 64-bit processor.
I think you are confused:
char
is 1 byte, but not defined for byte operation purpose. I believe there's another way to do this byte operation. What's the correct way to byte operation?
What exactly are you expecting byte
to mean, if not the exact same thing that char
means?
In C and in C++, chars are bytes. By definition. What is not the case is that bytes are necessarily octets. A byte contains at least 8 bits. There is no guarantee that a given platform even makes it possible to reference a chunk of memory that is exactly 8 bits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With