Monday, January 26, 2009

operator of Pointers

Two operators are provided that, when used, cause these two steps to occur separately.

operator

meaning

example

&

do only step 1 on a variable

&fl

*

do step 2 on a number(address)

*some_num


Try this code to see what prints out:

C Code Listing 2

1: #include
2: int main()
3: {
4: float fl=3.14;
5: printf("fl's address=%u\n", (unsigned int) &fl);
6: return 0;
7: }
C++ Code Listing 2
1:#include
2: int main()
3: {
4: float fl=3.14;
5: std::cout << "fl's address=" << (unsigned int) &fl <<>
2: int main()
3: {
4: float fl=3.14;
5: unsigned int addr=(unsigned int) &fl;
6: printf("fl's address=%u\n", addr);
7: return 0;
8: }

C++ Code Listing 3
1: #include
2: int main()
3: {
4: float fl=3.14;
5: unsigned int addr=(unsigned int) &fl;
6: std::cout << "fl's address=" << addr << std::endl;
7: return 0;
8: }




The above code shows that there is nothing magical about addresses. They are just simple numbers that can be stored in integer variables.

The unsigned keyword at the start of line (5) simply means that the integer will not hold negative numbers. As before, the (unsigned int) phrase has been shown in gray. It must be included for the code to compile, but is not relevant to this discussion. It will be discussed later.

Now let's test the other operator, the * operator that retrieves the contents stored at an address:

C Code Listing 4
1: #include
2: int main()
3: {
4: float fl=3.14;
5: unsigned int addr=(unsigned int) &fl;
6: printf("fl's address=%u\n", addr);
7: printf("addr's contents=%.2f\n", * (float*) addr);
8: return 0;
9: }

C++ Code Listing 4
1: #include
2: int main()
3: {
4: float fl=3.14;
5: unsigned int addr=(unsigned int) &fl;
6: std::cout << "fl's address=" << addr << std::endl;
7: std::cout << "addr's contents=" << * (float*) addr << std::endl;
8: return 0;
9: }

In line (7), step 2 has been performed on a number:
2. The contents stored at that address [addr] are retrieved.

In order to make line (7) work, a little "syntax sugar" had to be added for the program to compile. Like before, (float*) is shown in gray because it is not relevant to the current discussion. For the sake of this discussion, just read "*(float*)addr" as "*addr" (that is, ignore the stuff in gray). The code shown in gray will be discussed later.

No comments:

Post a Comment