Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to add 1 byte to a pointer in C/C++?

Tags:

c++

c

pointers

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.

like image 649
eonil Avatar asked Feb 06 '11 15:02

eonil


People also ask

Can you add 1 to a pointer?

Unlike regular numbers, adding 1 to a pointer will increment its value (a memory address) by the size of its underlying data type.

Can you add to a pointer in C?

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.

How do you increment a pointer 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.

What is the size of 1 character pointer in C?

Size of Character Pointer Output: The size of the character pointer is 8 bytes. Note: This code is executed on a 64-bit processor.


1 Answers

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.

like image 140
Karl Knechtel Avatar answered Oct 19 '22 03:10

Karl Knechtel