Jump to content
Hash, Inc. Forums

C++ study group weekly discussion thread

Recommended Posts

Week 11

  • sizeof and Arrays
  • sizeof and multi-dimensional arrays (maybe)


Lets suppose you had a chain of linked sausages...

<====> <====> <====> <====> <====> <====> <====> <====>. . .

... but can't count them individually.

If you could know the length of the whole chain, and the length of the first sausage, you could divide the length of the chain by the length of the single sausage to know how many sausages there were... and how many buns you would need to get for them!

20 feet of 0.5 foot sausages would be 40 sausages.


That is basically how Steve Purcell is using sizeof with arrays.

if we declares an Array

int sausages[10];

we can use the sizeof function to examine it. We can use


to get how many bytes the whole array uses



to get how many bytes the first array element uses.

We can use those to get the length of the array and assign that to a variable

numberOfElements = sizeof(sausages)/sizeof(sausages[0])

We can use that variable later in For loops or other code that needs to know how long the array was.


Why did we need to figure out how many elements were in the array if we already put a number in when we declared the array?

Because later on, as we develop the program, or re-use it for something else we may change the number in that declaration but we won't have to go through the rest of the program to change all the code that uses the length of the array... we have made the code figure that out for us!

Share this post

Link to post
Share on other sites

Week 12

Switch. Switch uses a number you give it to choose from among several numbered cases


Sample project

  • Get the user to enter an integer up to 8 digits
  • Figure out how many digits the number is
  • use Switch  to  announce "This number has... digits"

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...