Challenge Code SPOILER!


#1

The code challenge in chapter 8 seems really simple.

[code]#include <stdio.h>

int main (int argc, const char * argv[])
{
//Find the size of a float
printf(“A float uses %zu bytes.\n”, sizeof(float));

return 0;

}[/code]

I messed around to see how much a pointer to a float uses and a bunch of other types as well. The math challenges with what could be held in a short are more difficult for me to grasp as I am math challenged!


#2

That’s the code I came up with, too. Interesting that it’s showing float is the same size as int (4 bytes).


#3

my version

#include <stdio.h>

int main (int argc, const char * argv[])
{

    //obtaining the size of float
    printf("The Size of float on my mac is %zu \n", sizeof(float));
   
    
    return 0;
    
}

#4

I found myself defining a variable just to keep my head straight and using a pointer to that variable to get the size. Inefficient but helped me review what I’d learned a bit better. Your code is the way I’d do it in future though.


#5

I think just so there is some variety, I was playing around and came up with this code to allow me to practice using addresses.

float i; float *addressOfF = &i; printf("The size of a float is: %zu\n", sizeof(*addressOfF)); return 0;


#6

[quote=“mazztech”]I think just so there is some variety, I was playing around and came up with this code to allow me to practice using addresses.

float i; float *addressOfF = &i; printf("The size of a float is: %zu\n", sizeof(*addressOfF)); return 0;[/quote]

mmm… Ok, i’ve been messing around with your code trying to figure out how this pointer thing goes, and here comes my question:

if you take out the asterisk out from sizeof(*addresOfF) just like this:

float i; float *addressOfF = &i; printf("The size of this is: %zu bytes \n", sizeof(addressOfF)); return 0;

The result printed in the log is: “The size of this is: 8 bytes”. So… What is being calculated? the pointer itself?

Any help will be appreciated! :slight_smile:


#7

The size of the pointer is calculated.
If you change sizeof(addressOfF) in sizeof(float *) you should get the same.

See page 58 (just before the header NULL).


#8

[quote]The size of the pointer is calculated.
If you change sizeof(addressOfF) [color=#FF0000]in[/color] sizeof(float *) you should get the same.[/quote]
You probably meant to say :

[quote]The size of the pointer is calculated.
If you change sizeof(addressOfF) [color=#00BF00]to[/color] sizeof(float *) you should get the same.[/quote]


#9

[quote=“ibex10”][quote]The size of the pointer is calculated.
If you change sizeof(addressOfF) [color=#FF0000]in[/color] sizeof(float *) you should get the same.[/quote]
You probably meant to say :

[quote]The size of the pointer is calculated.
If you change sizeof(addressOfF) [color=#00BF00]to[/color] sizeof(float *) you should get the same.[/quote][/quote]
You’re correct!
Some stupid mistake in my translation… :wink: