Monday, January 26, 2009

Pointers in C and C++ - Using Variables

Essentially, the computer's memory is made up of bytes. Each byte has a number, an address, associated with it.

The picture below represents several bytes of a computer's memory. In the picture, addresses 924 thru 940 are shown.


Try:

C Code Listing 1

 1:#include 
 2:int main()
 3:{
 4:  float fl=3.14;
 5:  printf("%.2f\n", fl);
 6:  return 0;
 7:}

C++ Code Listing 1

 1:#include 
 2:int main()
 3:{
 4:  float fl=3.14;
 5:  std::cout <<>
 6:  return 0;
 7:}

At line (4) in the program above, the computer reserves memory for fl. In our examples, we'll assume that a float requires 4 bytes. Depending on the computer's architecture, a float may require 2, 4, 8 or some other number of bytes.

When fl is used in line (5), two distinct steps occur:

  1. The program finds and grabs the address reserved for fl--in this example 924.
  2. The contents stored at that address are retrieved

To generalize, whenever any variable is accessed, the above two
distinct steps occur to retrieve the contents of the variable.

The illustration that shows 3.14 in the computer's memory can be misleading.
Looking at the diagram, it appears that "3" is stored in memory location 924,
"." is stored in memory location 925, "1" in 926, and "4" in 927.
Keep in mind that the computer actually uses an algorithm to convert the
floating point number 3.14 into a set of ones and zeros. Each byte holds 8
ones or zeros. So, our 4 byte float is stored as 32 ones and zeros (8 per byte times 4 bytes).
Regardless of whether the number is 3.14, or -273.15, the number is always
stored in 4 bytes as a series of 32 ones and zeros.


1 comment:

  1. If you have a business and have no customer for business, then you can hire SEO Services Chandigarh India for certain sales leads, we will provide guaranteed leads for your business as per your requirement of your business.

    ReplyDelete