How many bytes?

Given that everything lives in memory and that you now know how to find the address where data starts, the next question is How many bytes does this data type consume?

Using sizeof() you can find the size of a data type. For example,

i​n​t​ ​m​a​i​n​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​i​n​t​ ​i​ ​=​ ​1​7​;​
 ​ ​ ​ ​i​n​t​ ​*​a​d​d​r​e​s​s​O​f​I​ ​=​ ​&​i​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​i​ ​s​t​o​r​e​s​ ​i​t​s​ ​v​a​l​u​e​ ​a​t​ ​%​p​​n​"​,​ ​a​d​d​r​e​s​s​O​f​I​)​;​
 ​ ​ ​ ​*​a​d​d​r​e​s​s​O​f​I​ ​=​ ​8​9​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​N​o​w​ ​i​ ​i​s​ ​%​d​​n​"​,​ ​i​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​n​ ​i​n​t​ ​i​s​ ​%​z​u​ ​b​y​t​e​s​​n​"​,​ ​s​i​z​e​o​f​(​i​n​t​)​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​ ​p​o​i​n​t​e​r​ ​i​s​ ​%​z​u​ ​b​y​t​e​s​​n​"​,​ ​s​i​z​e​o​f​(​i​n​t​ ​*​)​)​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Here there is yet another new token in the calls to printf(): %zu. The sizeof() function returns a value of type size_t, for which %zu is the correct placeholder token.

Build and run the program. If your pointer is 4 bytes long, your program is running in 32-bit mode. If your pointer is 8 bytes long, your program is running in 64-bit mode.

sizeof() will also take a variable as an argument, so you could have written the previous program like this:

i​n​t​ ​m​a​i​n​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​i​n​t​ ​i​ ​=​ ​1​7​;​
 ​ ​ ​ ​i​n​t​ ​*​a​d​d​r​e​s​s​O​f​I​ ​=​ ​&​i​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​i​ ​s​t​o​r​e​s​ ​i​t​s​ ​v​a​l​u​e​ ​a​t​ ​%​p​​n​"​,​ ​a​d​d​r​e​s​s​O​f​I​)​;​
 ​ ​ ​ ​*​a​d​d​r​e​s​s​O​f​I​ ​=​ ​8​9​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​N​o​w​ ​i​ ​i​s​ ​%​d​​n​"​,​ ​i​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​n​ ​i​n​t​ ​i​s​ ​%​z​u​ ​b​y​t​e​s​​n​"​,​ ​s​i​z​e​o​f​(​i​)​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​ ​p​o​i​n​t​e​r​ ​i​s​ ​%​z​u​ ​b​y​t​e​s​​n​"​,​ ​s​i​z​e​o​f​(​a​d​d​r​e​s​s​O​f​I​)​)​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset