offset meaning

I'm reading an e-book about C++ and found something i didn't understand.

When speaking of something like this:
 
  char* ptr = &charArray[0];


What does an offset mean? or an integer offset?
or what does an offset mean in general in programming?
Last edited on
An offset generally refers to a value that is added to another base value, usually a (base) pointer in order to access a single element in a sequential list of elements, usually an array.


Example:
- In your case ptr points to the 1st element of the array or charArray[0],
*ptr is therefore the value stored in charArray[0];
- If you'd like to address the 5th element you can add an OFFSET to ptr like
ptr = ptr + 4; Now *ptr is the value of the 5th element or charArray[4];
Last edited on
So is &charArray[4] also an offset? or only
ptr = ptr + 4;
?
Last edited on
"So is &charArray[4] also an offset? or only"
No this is generally not understood as an offset but a base address that refers to the 5th element.

I should have chosen a base pointer instead of adding the offset to the original pointer. I hope this is clearer

1
2
3
4
5
6
char* baseptr = &charArray[0];
char* ptr;

ptr =  baseptr + 4; //Offset is 4
ptr =  baseptr + 2; //Offset is 2
      
Last edited on
So whatever number you write in the brackets are the offset? or in other words the offset is the element you choose in the array (by number aka offset)?
Did i get it right?
no you still misunderstand.

The 4 in &charArray[4] is an INDEX.
The 4 in (ptr = baseptr + 4) is an OFFSET

Both might have the same outcome but they are not the same in terms of definition.
I think i get it now, thanks :)
Topic archived. No new replies allowed.