Categories > Coding > C++ >

Whats the difference between [] and +

icedmilke222

Squidward

Posts: 51

Threads: 15

Joined: May, 2022

Reputation: 2

Posted

uh idk what the difference is between [] and + when accessing a ptr

like

whats the different between

*(DWORD*)(ptr+off)

and

*(DWORD*)(ptr)[off]

  • 0

what sup

i lo re c++

Posts: 24

Threads: 0

Joined: Dec, 2022

Reputation: 5

Replied

[] defeferences, + doesnt

ptr + 5 is like &ptr[5]

  • 1

Posts: 228

Threads: 43

Joined: May, 2022

Reputation: -5

Replied

@RealNickk,

Nope, you're wrong. Learn about pointer arithmetic, his example is correct.

If you'd like to test it, go ahead and run the following:

int arr[]{1,2,3};
std::cout << &arr[2] << '\n';
std::cout << arr + 2;

And to answer icedmike's question:

*(DWORD*)(ptr+off)

 

Let's say ptr is a pointer to an int ( int* )

 

ptr + 2 will essentially do ptr + (2 * sizeof(int))

 

S if ptr points to 0x1000 then ptr + 2 will be 0x1008.

 

Whenever you add an integer to a pointer, the resulting type of the expression will be the type of the pointer, meaning *(ptr+2) is a valid C++.

So here, assuming ptr is of type int*, you're casting an int* to a DWORD* ( unsigned long pointer ) and then derefencing it, so semantically, all you're doing here is now interpreting that value as unsigned rather than signed.

 

*(DWORD*)(ptr)[off]

 

Here, the parentheses around ptr are completely useless and redundant, so we can remove them to have this:

*(DWORD*)ptr[off]

 

So here, we are using the subscript operator( [] ) to index the nth element of this array ( or pointer ( pointers and arrays are not synonymous ), you can use the subscript operator on pointers and arrays ) and then you're casting that element to a DWORD*, and then dereferencing it.

 

 

 

 

  • 1

https://media.discordapp.net/attachments/1044764388546068510/1051935933836050482/Signature_4.png

Users viewing this thread:

( Members: 0, Guests: 1, Total: 1 )