Here is a nice source example which can help you understand C/C++ pointers operations much better. #include <stdio.h> So, lets take a look at this example. We have our own structure type TestCase. And we use "tests" pointer to pointer to TestCase to define an array of TestCase objects. To store these objects, we use malloc first to allocate memory for the whole array and then to allocate memory for every element of the array in loop.
In the next loop we set ida and idb parameters of the TestCase objects to some values (i and i+6 accordingly). And next goes something, that makes this example so good for education purposes. *(long*)((long)(long*)(tests[i])+(long)&(((TestCase *)NULL)->idb)) This line is the same thing as *tests[i]->idb. But lets see, how it works. Lets start with (long)&(((TestCase *)NULL)->idb)). 1. "(TestCase *) NULL" will be treated as a TestCase object which is located at NULL address, which is 0. 2. "->idb" will take the offset of the idb parameter from the TestCase object position in memory (so, NULL + offset(idb)) and return its value. 3. But we don't need here value of the idb parameter but its offset in memory from the TestCase object in bytes, that is why we use & operator, which makes program to return address of the variable instead of its value. So "(long)&(((TestCase *)NULL)->idb)" means "return long (for x64 processors) address of the idb parameter of the TestCase object that is located at NULL address in memory". This is how we will find out the offset of the idb parameter from its TestCase root address in memory. It will be the same for all TestCase objects. If we add this offset to tests[i], which represents the address of TestCase object with index i in memory, we'll get the address of its idb parameter. Next we need to take a value from this address. So we convert this address to a pointer, then take long address of this pointer ((long)(long*)) and after that we take a value to which points this address *(long*). So, that is the equality of the tests[i]->idb record.
0 Comments
Leave a Reply. |
NoticeI have removed Russian content from my website and now will post articles in English only. This is not because of some politics, Russian speaking people you are great, but just it is very hard to support bilingual web site in Weebly. For those who read my articles as usual I ask to click on a single advertisement banner on my web site. This gives me some credits and is free of charge for you. Archives
August 2016
Categories
All
|