Confusing Pointer arithmetic

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
	/// \ ARGUMENT STRING
	unsigned char hex[] = {	0x2D, 0x6D, 0x20, 0x74, 0x6F, 0x6D, 0x74, 0x6F, 0x6D, 0x5F, 0x75, 0x74, 0x72, 0x65, 0x63, 0x68, 0x74, 0x5F, 0x32, 0x30, 0x30, 0x38, 0x5F, 0x30, 0x34, 0x2E, 0x64, 0x62, 0x33, 0x20, 0x2D, 0x69, 0x20, 0x22, 0x4C, 0x3B, 0x49, 0x44, 0x3B, 0x30, 0x2C, 0x30, 0x2C, 0x31, 0x35, 0x32, 0x38, 0x30, 0x30, 0x30, 0x31, 0x32, 0x32, 0x39, 0x35, 0x32, 0x34, 0x2C, 0x31, 0x35, 0x32, 0x38, 0x30, 0x30, 0x30, 0x31, 0x33, 0x34, 0x39, 0x34, 0x39, 0x38, 0x2C, 0x2D, 0x31, 0x35, 0x32, 0x38, 0x30, 0x30, 0x30, 0x31, 0x33, 0x34, 0x39, 0x35, 0x30, 0x30, 0x22, 0x20, 0x2D, 0x69, 0x66, 0x20, 0x4C, 0x4F, 0x43, 0x41, 0x54, 0x49, 0x4F, 0x4E, 0x5F, 0x53, 0x54, 0x52, 0x49, 0x4E, 0x47, 0x20, 0x2D, 0x6F, 0x66, 0x20, 0x42, 0x49, 0x4E, 0x41, 0x52, 0x59, 0x36, 0x34, 0x00};
	unsigned char *anchor_s = &hex[0];
          unsigned char *t_in = anchor_s;
          // count characters --> amount 122
	int totalSRC = 0;
	while(*t_in++) totalSRC++;

          // jchar size is NOT 1 byte!
          // jchar size is 2 byte
          // see %JDK%\include\jni.h
 	jchar * pDestItem = new jchar [totalSRC+1];
	jchar *anchor_dest = pDestItem;
	t_in = anchor_s;
          
          // copy each 1byte item to place with 2byte space for each item
	while(*(t_in)) { 
		*pDestItem = *t_in; 
		++pDestItem; 
		++t_in; 
	}
	*(pDestItem) = 0x00; //nullbyte at the end

// when i have 122 char (=8bit=1byte) items i have then 122bytes in memory
// this is right <-- dif_c is 122
	int dif_c = t_in - anchor_s;

// when i have 122 jchar (=16bit=2byte) items i have then 122 characters, but 2 bytes per jchar, thus 244 bytes total
// according to adresses this is right, 0x00916DE4 - 0x00916CF0 = 0xF4 = 244
// but dif_j says 122 ???? is it just counting the characters?
	int dif_j = pDestItem - anchor_dest;

	//return env->NewStringUTF(dynamic_cast<unsigned char *>(t_in));
	return anchor_dest;


Why has my dif_j the value 122 and not 244??? I hope I could make my problem clear?

Cheers Huck
Last edited on
You couldn't come up with a simpler example than this?
Because pDestItem == anchor_dest + 122. int dif_j = pDestItem - anchor_dest;
is not the same as
int dif_j = (long)pDestItem - (long)anchar_dest;

Think about it in this way.
1
2
3
4
5
int a[100];
int *p = &a[0]; //this is equal to int *p = a
int *q = &a[10]; // this is equal to int *q = a + 10
int distance_between_pointers = q - p; //10
int distance_between_addresses = (int)q - (int)p; //40 

For more infomation, refer to a book:)
Last edited on
Yes you're right. I should have cast adreesses!

Its workingh. Thank you.


Pointer difference always returns element difference, not byte difference.
1
2
3
int a[]={2,4,6,8};
int *b=a,c=a+3;
std::cout <<*b<<std::endl<<*c<<std::endl<<(c-b)<<std::endl;

EDIT: Dammit! Oh, well.
Last edited on
Topic archived. No new replies allowed.