-
simple pointers question
Hello, I have two pointers:
unsigned char *rdata
and unsigned char *rdata_tail
rdata_tail will always represent a memory location greater than or equal to rdata
Let's say the memory that rdata starts at is like such: "hello"
(but the program doesnt know this)
rdata_tail gives the memory address after "o"
My question is, how do I get the number 5 using these 2 pointers?
Thanks :)
-
What do you mean get the number 5? Like a value of 5(int) from a char?
-
no =/
like this:
memory:
-1-2-3-4-5-
[h][e][l][l][o]
i want to subtract memory address 2 from memory address 1
and get 5 because memory address 2 is 5 unsigned chars ahead of memorry address 1
-
Code:
// did you try it?
unsigned char *rdata = // the start of a block of memory
unsigned char *rdata_tail = // supposedly the end of a block of memory or something.
rdata = rdata+2 - rdata_tail;
Note that pointer arithmatic is dangerous, but rdata now points to the area you want by assigning the pointer elsewhere.
-
You're doing it backwards. The "tail" is greater than the "head". Thus you subtract head from tail, not the other way around. There is also a variable type for just this type of thing:
Code:
ptrdiff_t len = tail - head;
Quzah.