    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Student Code Critique Competition 26</title>
        <link>https://members.accu.org/index.php/articles/184</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Student Code Critiques from CVu journal. + CVu Journal Vol 16, #1 - Feb 2004</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c184/">Journal Columns</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c183/">Code Critique</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c104/">161</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-183-104/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+183+104/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Student Code Critique Competition 26</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 01 February 2004 01:21:34 +00:00 or Sun, 01 February 2004 01:21:34 +00:00</p>
<p><strong>Summary:</strong>&nbsp;This item is part of the Dialogue section of C Vu, which is intended to designate it as an item where reader interaction is particularly important. Readers&#8217; comments and criticisms of published entries
are always welcome.</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2>Before We
Start</h2>
</div>
<p>I have become accustomed to an ever growing stack of books
waiting for me to get round to reading them (for the first time
forty-five years I have failed to read a serial in Analog as soon
as the last part was published). What came as a surprise was to
realise that writing that I am committed to is going the same way -
the stack is growing faster than I can reduce it. Some things have
to be done by me but other things could be done by others if they
had the will to do so.</p>
<p>This column is one of the latter. Its contents are largely
written by others. Putting it together takes roughly a day's work.
Is there anyone reading this who would be willing to take it over?
I can continue to manage the supply of prizes but freeing up
another day would be much appreciated.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2>Student Code
Critique 24 revisited</h2>
</div>
<p>For some reason some of my email has been disappearing before it
reaches me (and as my ISP does not yet apply any filters, though
they will soon, it isn't caused by some form of false positive for
spam). I keep complete logs of all mail that reaches my mailbox and
can identify several places where people have clearly sent me
things that have never arrived (what worries me is the cases I do
not know of, but note that I always acknowledge email with
content).</p>
<p>It seems that two entries for SCC 24 were consumed by this email
eating demon. So here they are but without the restatement of the
problem.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3>From Matthew
Towler <tt class="email">&lt;<a href=
"mailto:towler@ccdc.cam.ac.uk">towler@ccdc.cam.ac.uk</a>&gt;</tt></h3>
</div>
<p>This program is simply outputting text so first of all I will
suggest coding purely in standard C++ and removing the MSDOS
specifics. These are <tt class="function">clrscr()</tt> (more on
this in a moment) and <tt class="function">getch()</tt> which I
think is being used to wait for a character to be pressed between
groups of output. Removing these means we can also remove
<tt class="literal">&lt;conio.h&gt;</tt>.</p>
<p>The first line of <tt class="function">main()</tt> is <tt class=
"literal">void clrscr();</tt> I guess this is intended to call an
MSDOS function to clear the screen, but in fact it declares a
function named <tt class="function">clrscr</tt> taking no
parameters and returning nothing - but does not call this
function.</p>
<p>The simplest way to get the output into a text file would be to
redirect the output. Assuming the code compiles to an executable
named <span class="application">Sum.exe</span>, then this would be
achieved from the command line (from the directory containing
<span class="application">Sum.exe</span>) as follows:</p>
<pre class="screen">
Sum &gt; output.txt
</pre>
<p>Then the following should open the complete output in
notepad</p>
<pre class="screen">
notepad output.txt
</pre>
<p>The output might be enhanced by adding some separators e.g.</p>
<pre class="programlisting">
std::cout &lt;&lt; x &lt;&lt; '\t' &lt;&lt; m &lt;&lt; '\t';
</pre>
<p>would output the values of <tt class="varname">x</tt> and
<tt class="varname">m</tt> with a tab character in between.</p>
<p>The headers <tt class="literal">&lt;iostream.h&gt;</tt> and
<tt class="literal">&lt;iomanip.h&gt;</tt> are not standard, they
are old pre-standard headers and should be replaced by <tt class=
"literal">&lt;iostream&gt;</tt> and <tt class=
"literal">&lt;iomanip&gt;</tt>. This will mean that <tt class=
"literal">cout</tt> and <tt class="literal">setw</tt> will need to
be additionally qualified with <tt class="literal">std::</tt>.
<tt class="literal">&lt;math.h&gt;</tt> is standard but deprecated,
you should really use <tt class="literal">&lt;cmath&gt;</tt> which
would place the <tt class="function">pow()</tt> function in the
<tt class="literal">std</tt> namespace. However in practice
compiler support for &lt;cmath&gt; is patchy, and all will provide
<tt class="literal">&lt;math.h&gt;</tt> for C compatibility so I
usually stick with <tt class="literal">&lt;math.h&gt;</tt>.</p>
<p>My next point is that of named constants. The values <tt class=
"constant">1</tt>, <tt class="constant">11</tt>, <tt class=
"constant">25000</tt>, <tt class="constant">35000</tt>, <tt class=
"constant">5000</tt> and <tt class="constant">2</tt> appear several
times each in the code. I am not sure what the code is calculating
but it is likely the meaning would be much clearer if the constants
were named to indicate their meaning or purpose. This would
emphasise the connections between the individual loops and the data
they are handling and just as importantly it would reduce the
likelihood of a single typo breaking the code.</p>
<p>Some more informative naming of variables would also help.
<tt class="varname">i</tt>, <tt class="varname">r</tt>, <tt class=
"varname">j</tt>, <tt class="varname">m</tt> and <tt class=
"varname">x</tt> leave the reader in the dark about what sort of
calculation is being performed, and also give a higher probability
of errors due to typos.</p>
<p><tt class="varname">Sum</tt> is declared <tt class=
"literal">static</tt>, which for a program consisting of a single
non-recursive function does not significantly alter the meaning.
The only advantage of this is that it will not allocate 25000
<span class="type">int</span>s on the stack; MSDOS often has a
fairly small stack and this could be important. <tt class=
"varname">Sum</tt> is not declared with a type, so it is using the
deprecated <span class="type">implicit int</span> C feature. Most
modern compilers will now warn about this and a few will refuse to
compile the code.</p>
<p>An alternative to this two dimensional array would be a
<tt class="literal">std:vector&lt; std::vector&lt; int&gt;
&gt;</tt>. This would allow the access syntax to be changed from
<tt class="literal">Sum[i][j]</tt> to <tt class=
"literal">Sum.at(i).at(j)</tt> which will check all accesses are
within limits at run time. This could be a helpful debugging aid in
a simple program such as this where efficiency is not paramount.
The equivalent declaration of <tt class="varname">Sum</tt> is as
follows.</p>
<pre class="programlisting">
std::vector&lt; std::vector&lt;int&gt; &gt;
    Sum(5000, std::vector&lt;int&gt;(5000));
</pre>
<p>Use of <tt class="classname">std::vector</tt> would also mean
that all the integer values in <tt class="varname">Sum</tt> would
be automatically initialised to zero, as opposed to the static data
which will not do this [<i><span class="remark">actually, you are
mistaken, static data is zero-initialised by default -
Francis</span></i>].</p>
<p>It usually aids readability if variables are declared to exist
for the shortest time; and initialised as they are declared. For
instance <tt class="varname">r</tt> is only used within the first
<tt class="literal">for</tt>-loop and initialised at the end of the
loop; it could be declared and initialised at the top of this loop.
The advantage of this is that when reading code there are less
lines to search for the variable. <tt class="varname">r</tt> is
currently being used uninitialised; but I did have to think for a
long time to work out (and changed my mind several times) whether
or not the loop bounds in the nested loops conspired to initialise
it before first use. It is exactly this sort of confusion that this
guideline is intended to avoid.</p>
<p>Similarly the loop variables could be declared within the loops
e.g.</p>
<pre class="programlisting">
for(int i =1; etc.
</pre>
<p>The code inside the first pair of nested for loops would be
simpler if the <tt class="literal">if(i == 1)</tt> block were moved
above the inner loops and the inner loop started at <tt class=
"constant">2</tt>. This saves an <tt class="literal">if()</tt> per
loop, and far more importantly clarifies the intent that this code
is setting up the calculation for the subsequent iteration.</p>
<p>Finally, I am not sure about the mixing of floating point and
integers in the loop conditions; namely</p>
<pre class="programlisting">
i &lt;= pow(2, j)
</pre>
<p>in the first loops and similarly for <tt class="varname">x</tt>
and <tt class="varname">m</tt> in the second loops.</p>
<p>In <tt class="literal">math.h</tt>, <tt class=
"function">pow()</tt> is declared as</p>
<pre class="programlisting">
double pow(double, double);
</pre>
<p>Standard C++ (but not C) also provides an overload (according to
Stroustrup 3<sup>rd</sup> Ed).</p>
<pre class="programlisting">
double pow(double, int).
</pre>
<p>Which overload is called is irrelevant as the problem lies with
the <span class="type">double</span> return value. For example if
<tt class="literal">i = 4</tt> and <tt class="literal">j = 2</tt>
the expression resolves to <tt class="literal">4 &lt;= 4.0</tt>,
which may not compare as you expect. To perform the comparison the
inton the left will first be promoted to a double, which will
result in an approximation of the integer value such as 3.999999.
This small error can in some cases change the result of the
comparison [<i><span class="remark">True in theory but all
compilers I know of correctly and exactly represent the floating
point equivalents of whole numbers provided as constants - it is
the computed value which is suspect not the conversion from int to
double. Francis</span></i>].</p>
<p>The solution to this is to write a function to call <tt class=
"function">pow()</tt> and perform the comparison with a tolerance
to take account of any approximation errors.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3>
</div>
<p>[<i><span class="remark">Sorry, but I really do not have time to
go through my email archives looking for names of authors. If you
send me a file I save it for future processing. If you leave your
name out of the file, your work will be published anonymously.
Francis</span></i>]</p>
<p>My comments to Student Code Critique 24 are split into two
parts. The first part describes the changes needed to get the
required behaviour of the program. the second shows a number of
ways the code could generally be improved.</p>
<div class="sect3" lang="en">
<div class="titlepage">
<h3>Solving the
problem</h4>
</div>
<p>Rewriting the program to make it write data to a file requires
very little. A few changes to existing code and a couple of new
lines does the job:</p>
<p>Taken from the top the changes are:</p>
<p>Add a new <tt class="literal">#include</tt> statement:</p>
<pre class="programlisting">
#include &lt;fstream&gt; //file handling
</pre>
<p>The line:</p>
<pre class="programlisting">
void main(){
</pre>
<p>should be changed into:</p>
<pre class="programlisting">
int main( int argc, char* argv[] ){
</pre>
<p>The standard mandates a return type of int, the 2 parameters
gives us access the command line parameters, which we will use to
name the file to write the data to. Insert the following to achieve
this. [<i><span class="remark">If you choose that mechanism you
should first check that there is a second command line argument and
check that the file is successfully opened.</span></i>]</p>
<pre class="programlisting">
// open an output file named by the first
// argument to the program.
std::ofstream output(argv[1]);
</pre>
<p>Change the line:</p>
<pre class="programlisting">
cout &lt;&lt; x &lt;&lt; m &lt;&lt; setw(10)
     &lt;&lt; Sum[x][m] &lt;&lt; '\n';
</pre>
<p>to</p>
<pre class="programlisting">
output &lt;&lt; x &lt;&lt; m &lt;&lt; setw(10)
       &lt;&lt; Sum[x][m] &lt;&lt; '\n';
</pre>
<p>and the data will be written to the file named as the first
argument to the program on the command line.</p>
<p>This makes the program write data to a named file instead of
<tt class="literal">stdout</tt>. [<i><span class="remark">Note I
edited the submitter's std::out - there is no such
thing.</span></i>]</p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3>Improving the
code</h4>
</div>
<p>The code contains a lot of unnecessary noise. Removing this
noise can lead to a program that is significantly easier to read
and understand. Removing the noise also increases the programmer's
trust in the output of the program.</p>
<p>I have grouped the noise into categories, trying to isolate the
core of each problem. My hope is that it will help recognizing the
type of problems in the future.</p>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>
</div>
<p><tt class="literal">#includes</tt> should follow the C++
standard and use the include files without the <tt class=
"literal">.h</tt> extension. The C header for math should be
replaced by cmath, which includes the math definitions in the std
namespace.</p>
<p>Some of the <tt class="literal">#include</tt> statements in the
program are not necessary, and they should be removed from the
code. Include statements which are not used add false
dependencies.</p>
<p>For large programs with a lot of header files, the false
dependencies can forces a recompilation of an otherwise unchanged
compilation unit. On a heavily loaded machine the reading and
parsing of the include files can be a large part of the total
compilation time.</p>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>Forward
declarations:</h5>
</div>
<p>Forward declarations of functions and variables should be
deferred to the latest possible time. This ensures that the
declaration is made as close to point where it is used as possible.
A consequence of this is the removal of declarations that are not
used.</p>
<p>Following this advice, we remove the lines:</p>
<pre class="programlisting">
void clrscr();
int i, r, j, m, x;
</pre></div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>
</div>
<p>One should try to only use arrays of the needed size. Allocating
more memory than we need might be masking that we do not really
know how memory is used. It could be hiding an error in indexing,
which could be hard to spot, even when using memory bounds
checkers.</p>
<p>A simple scan of the code that assigns to the array <tt class=
"varname">Sum</tt> shows that the variable <tt class=
"varname">j</tt>, which is used as the second index into the array,
only indexes the range [1:11]. If we change the declaration of the
array <tt class="varname">Sum</tt> to reflect this usage, we reduce
the amount of memory required by a factor of 454.</p>
<p>The first index <tt class="varname">i</tt> runs in the interval
[1:2048], which leads to a reduction of the needed memory by a
factor of approximately 2.5, all in all we are able to reduce the
memory need of the program by a factor of over 1100.</p>
<p>The indexing into the array is done from 1. The C and C++ arrays
are normally indexed from 0, but adapting an existing algorithm
that used indexing from 1 can lead to problems.</p>
<p>This is especially important if the code might be used by
others, or if the code will be used again and again over a period
of years. It will be a lot easier to see the connection between the
algorithm and the code if we keep indexing from 1.</p>
<p>The declaration of the array should look like this:</p>
<pre class="programlisting">
long Sum[2049][12]
</pre>
<p>The keyword static that was previously used is not necessary
[<i><span class="remark">I think the writer has missed the
significance of using static to both ensure default initialisation
and to use 'static' memory provided at load time rather than,
possibly precious, stack memory.</span></i>] The size of the array
has taken into account that the indexing starts at 1.</p>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>
</div>
<p>The <tt class="literal">for</tt>-loops should declare the type
of the counting variable it uses inside the <tt class=
"literal">for</tt>-statement. This makes sure that the counting
variable is only visible inside the for-loop [<i><span class=
"remark">As this was for an MSDos platform, that might not be
true</span></i>].</p>
<p>The inner <tt class="literal">for</tt>-loop contains the
construction:</p>
<pre class="programlisting">
for(int i = 1; i &lt; pow(2,j); i++) {
// code //
  i = i + 1;
}
</pre>
<p>Because the code block spans several lines, it is not
immediately obvious that the <tt class="literal">for</tt>-loop step
size is two and not one. This should be written as:</p>
<pre class="programlisting">
for( int i = 1; i &lt; pow( 2, j ); i =+ 2 ) {
// code //
}
</pre>
<p>The innermost loop has the following construction:</p>
<pre class="programlisting">
for(i ......) {
  if(i == 1) {
  // code //
  }
  if(i &gt; 1) {
// Code using variable r
    r = r + 1
// code not using variable r
  }
  r = 2;
}
</pre>
<p>From the above it should be obvious that every time <tt class=
"varname">r</tt> is used, it has the value 2, and we might as well
change the single usage of <tt class="varname">r</tt> to using a
properly named variable, like</p>
<pre class="programlisting">
const long magic_constant = 2;
</pre>
<p>Making it obvious that the code depends on a magic constant.</p>
<p>To ease the reading of the <tt class="literal">for</tt>-loops
writing the data, these loops should use the same variables as was
used to generate the data:</p>
<pre class="programlisting">
for(int j = 1; j &lt;= 11; ++j) {
  for(int i = 1; i &lt;= pow(2.0, j ); i++) {
    output &lt;&lt; i &lt;&lt; &quot; &quot; &lt;&lt; j
           &lt;&lt; setw(10) &lt;&lt; Sum[i][j]
           &lt;&lt; '\n';
    output &lt;&lt; i &lt;&lt; &quot; &quot; &lt;&lt; j
           &lt;&lt; setw(10) &lt;&lt; Sum[i][j]
           &lt;&lt; '\n';
  }
}
</pre>
<p>The innermost loop for writing the data two times could be
changed to two lines, writing the same output. This makes it more
obvious that the data is written twice, at the cost of making all
changes to the writing code in both places, but the eye is quite
good at catching differences in lines that should look the
same.</p>
<p>The post increment operator used in the forloops, should be
changed to the pre increment operator, if not the code will
generate a temporary to hold the value before incrementing, that
will never be used.</p>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3><a name="d0e465" id=
"d0e465"></a>Readability:</h5>
</div>
<p>The use of space characters in the code, can significantly
increase readability, especially if used in a consistent way, like
always enclose operators like <tt class="literal">+</tt>,
<tt class="literal">-</tt>, <tt class="literal">*</tt>, <tt class=
"literal">/</tt>, <tt class="literal">=</tt>, <tt class=
"literal">==</tt>, <tt class="literal">&lt;=</tt> and so on with an
equal amount of space before and after. [<i><span class=
"remark">However placing spaces after any form of open bracket and
before any form of close bracket often reduces readability. In
addition there are good readability arguments for not placing
spaces either side of a strongly binding operator such as
<tt class="literal">*</tt> or <tt class=
"literal">/</tt>.</span></i>]</p>
<p>The rule could read something like: Binary operators have an
equal amount of one or more space characters on both sides.</p>
<p>The difference is clearly seen comparing two versions of the
first for statement:</p>
<pre class="programlisting">
for(j=2;j&lt;=11;j++)
</pre>
<p>and</p>
<pre class="programlisting">
for ( j = 2; j &lt;= 11; j++ )
</pre>
<p>[<i><span class="remark">Yet is not:</span></i></p>
<pre class="programlisting c3">
<span class="remark">for(j = 2; j &lt;= 11; j++)</span>
</pre>
<p><i><span class="remark">slightly more readable? Too much space
can be as bad as too little.</span></i>]</p>
<p>All in all the code ends up looking like this:</p>
<p>[<i><span class="remark">snipped</span></i>]</p>
<p>This code generates the same output as the sample output, except
that a space is inserted between the writing of the two array
indexes.</p>
</div>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2>Student Code
Critique 25 entries</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3>The
problems</h3>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3>
</div>
<p>I am little confused about return values of <tt class=
"literal">sizeof</tt> operator.</p>
<p>Here is a simple C program which is putting me in doubt:</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;
int main() {
  int a[10];
  int *p =(int *) malloc (10);
  printf(&quot;Size of a = %d \n&quot;,sizeof(a));
  printf(&quot;Size of p = %d \n&quot;,sizeof(p));
}
</pre>
<p>Output is :</p>
<pre class="screen">
Size of a = 40
Size of p = 4
</pre>
<p>My understanding says even array name is a pointer. If so why it
does not show <tt class="literal">sizeof(a)</tt> as 4? Or if
<tt class="literal">sizeof</tt> shows the total allocated memory
then why <tt class="literal">sizeof(p)</tt> does not show 10?</p>
<p class="c2"><span class="remark">There are numerous errors in
both the code and the student's understanding. Please address these
comprehensively, perhaps including places where your explanation
would be different if this were a C++ program.</span></p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3>
</div>
<p>I am getting an error linker error. Here is the code:</p>
<pre class="programlisting">
// Define Libraries
#include &lt;stdio.h&gt;
#include &lt;math.h&gt;
//Start Of Main Program
main() {
  double hypo, base, height;
/* Enter base and height */
  printf(&quot;Enter base:&quot;);
  scanf(&quot;%f&quot;, &amp;base);
  printf(&quot;Enter height:&quot;);
  scanf(&quot;%f&quot;, &amp;height);
  hypo = sqrt(pow(base, 2)+pow(height, 2));
  printf(&quot;hypotenuse is %f&quot;, &amp;hypotenuse);
}
</pre>
<p class="c2"><span class="remark">Ignore the question asked by the
student and address the serious problems with the code
itself.</span></p>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3>From Annamalai
Gurusami <tt class="email">&lt;<a href=
"mailto:annamalai.gurusami@email.masconit.com">annamalai.gurusami@email.masconit.com</a>&gt;</tt></h3>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>Provide
Prototypes</h5>
</div>
<p>It is a good practice to include all the relevant header files
(meaning, provide the proper prototypes), even though it is not
mandatory as far as the C programming language is concerned. (It is
compulsory in C++). For using <tt class="literal">malloc</tt>,
include the <tt class="literal">stdlib.h</tt> header file, so that
the necessary prototypes are provided to the compiler.</p>
<p>In the absence of an appropriate prototype, the compiler would
assume that the return type is an integer (while malloc function
actually returns a void pointer). This is fine in a 32-bit system,
but will be a problem on a 64-bit system. The reason is that in a
32-bit system, an integer and a pointer occupy the same amount of
memory space (four bytes), whereas in a 64- bit system, an integer
occupies 4 bytes, but the pointer occupies 8 bytes. So provide
prototypes. It might save you a lot of trouble later.</p>
<p>[<i><span class="remark">The above paragraph contains a number
of misconceptions. There is no requirement on any system that any
integer type have the same amount of storage as any pointer type.
Note that not only does both C &amp; C++ allow pointers to
different fundamental types to be different in both size and
layout, but some implementations actually use this license. The
requirements are that <span class="type">void*</span> and
<span class="type">char*</span> be identical in size and layout;
<span class="type">void*</span> must be able to store the value of
any data pointer without loss of information and that all pointers
to struct (and, in the case of C++, class) only need a declaration
of the type name. Different types of pointer can, and sometimes
are, different sizes. Pointers can, and sometimes are laid out
differently to the layout of an <span class=
"type">int</span>.</span></i></p>
<p><i><span class="remark">Lastly, as of the 1999 release of C,
implicit <span class="type">int</span> and implicit function
declarations are no longer supported. Francis</span></i>]</p>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>Array Name Is
Not A Pointer</h5>
</div>
<p>An array name is not exactly a pointer [1], even though in many
circumstances it degenerates into one. An array is a single entity,
in the sense that its name and its memory location are inseparable.
When we declare a variable like <tt class="literal">int a[10];</tt>
we have an object that can hold 10 integers and it is named
<tt class="varname">a</tt>. There is no other memory associated
with that object. When we just use an array name where a pointer is
expected (type being appropriate), it is interpreted as a pointer
to the first element of the array. In our case, if we use a, where
an <span class="type">int*</span> is expected, then it is evaluated
as <tt class="literal">&amp;a[0]</tt>. This dirty work is done by
the compiler. Also note that this association cannot be changed.
For example, we cannot do something like</p>
<pre class="programlisting">
int a[10];
a = malloc (10);
// *ERROR* cannot reassign another object to a
// a is not a pointer variable.
</pre>
<p>This is why <tt class="literal">sizeof(a)</tt> gives the size of
the array object named <tt class="varname">a</tt>. The size of a in
our case is <tt class="literal">10*sizeof(int)</tt> which is often
equal to 40.</p>
<p>The confusion mainly comes because of the applicability of the
subscript operator to an array and a pointer pointing to a
<tt class="literal">malloc</tt>'ed memory location. For
example,</p>
<pre class="programlisting">
int a[10];
int *p = malloc(10*sizeof(int));
// initialize a[0]...a[9] and p[0]...p[9]
for(int i=0; i &lt; 10; ++i) {
  printf(&quot;p[%d]=%d\n&quot;, i, p[i]);
  printf(&quot;a[%d]=%d\n&quot;, i, a[i]);
}
</pre>
<p>The similarity between these two usages is the main reason for
the confusion that an array name is a pointer. But one should
remember that the &quot;array&quot; <tt class="varname">p</tt> is not a
single entity. There are two entities involved - one is the pointer
variable <tt class="varname">p</tt>, and another is the allocated
memory that can hold 10 integers. Also the association between the
allocated memory and the pointer variable is only temporary, in the
sense that the pointer variable can be made to point to another
memory location. For example:</p>
<pre class="programlisting">
int a[10];
int *p = malloc(10*sizeof(int));
// initialize appropriately
p = a; // correct: evaluated as &amp;a[0]
a = p; // error: a cannot be re-assigned.
</pre>
<p>I leave it as an exercise to the reader to convince
himself/herself that an array name is not a const pointer.</p>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>The behaviour of
<tt class="literal">sizeof</tt> operator</h5>
</div>
<p>The <tt class="literal">sizeof</tt> operator is evaluated at
compile time. And it gives the size of the object that is given as
an operand. So:</p>
<pre class="programlisting">
int a[10];
sizeof(a);
// evaluates to the size of 10 integers
char *p = malloc(n);
sizeof(p);
// evaluates to the size of the pointer p
// which is independent of n.
</pre>
<p>Note that the type of the result of <tt class=
"literal">sizeof</tt> operator is <tt class="literal">size_t</tt>
(which is <span class="type">unsigned int</span> or <span class=
"type">unsigned long</span> [Or some other <span class=
"type">unsigned integer</span> type]). So check for the appropriate
format specifiers in your system and use it in the <tt class=
"function">printf</tt> statements.</p>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>The argument to
malloc</h5>
</div>
<p>In the provided program, the argument to <tt class=
"literal">malloc</tt> is 10 (which is in <span class=
"type">unsigned char</span>). The size of an <span class=
"type">integer</span> [<i><span class="remark">on this
system</span></i>] is 4 bytes. So the value provided to <tt class=
"literal">malloc</tt> is not in multiples of the size of an
<span class="type">int</span>. This most probably will result in
hard-to-find bugs (because of memory alignment problems.
[<i><span class="remark">Not likely, malloc is required to return
suitably aligned memory for any type</span></i>]) Also the
behaviour might depend on the implementation of <tt class=
"literal">malloc</tt>. Whatever the after effects, the provided
code doesn't seem to reflect what the user wants. If the user wants
to store 10 integers, then (s)he has to calculate the required size
manually, by doing <tt class="literal">10*sizeof(int)</tt>, and
passing that to <tt class="literal">malloc</tt>.</p>
<p>If it was C++, things are more clear. For an array of 10
integers, we can just write</p>
<pre class="programlisting">
int *p = new int[10];
</pre></div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>Casting the
<span class="type">void*</span> returned by <tt class=
"literal">malloc</tt></h5>
</div>
<p>Since the function <tt class="literal">malloc</tt> returns a
pointer of type void (a <span class="type">void*</span>), there is
no need to cast it explicitly. A <span class="type">void*</span>
can be assigned to other pointers without any explicit cast
[<i><span class="remark">In C but not in C++</span></i>]. In C++,
it is recommended to use the <tt class="literal">new</tt> for
allocating memory, which returns a pointer to the type asked for.
operator [<i><span class="remark">Not really, the memory allocation
tool in C++ is operator new, the creation of dynamic objects is
done with a new expression</span></i>] Since no generic pointer
types are involved, there is no question of casting.</p>
</div>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>Compilation
Errors</h5>
</div>
<p>The use of <tt class="varname">hypotenuse</tt> instead of
<tt class="varname">hypo</tt> in the last <tt class=
"literal">printf</tt> statement will result in compilation error.
Also if it was C++, the compilation would fail because the return
type of <tt class="function">main()</tt> is omitted.
[<i><span class="remark">Also true in C99</span></i>]</p>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>Comment on
Comments</h5>
</div>
<p>Comments are normally used to explain what a particular piece of
code does (if that cannot be easily understood, just by reading it)
and why. Comments like <tt class="literal">// Start of Main
Program</tt> are really superfluous, and do not add value. Also
wrong comments can be very harmful. For example, the comment
<tt class="literal">// Define Libraries</tt> is not correct. The
header files just provide declarations. Any declared functions are
defined elsewhere.</p>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>Flushing the
standard output</h5>
</div>
<p>When a prompt needs to be displayed to the user, it is always
prudent to flush the standard output (because a prompt normally
doesn't terminate with a new line). If this is not done, then it is
not guaranteed to be displayed on the terminal, because most of the
terminal drivers are line buffered. [<i><span class="remark">But
most, if not all, flush <tt class="literal">stdout</tt> before
collecting input from <tt class=
"literal">stdin</tt>.</span></i>]</p>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>Input Validation
And Error Checking</h5>
</div>
<p>There is no validation done on the provided input. The following
checks can be performed on the input. Check if they are legal
numbers. Check if they are greater than zero.</p>
<p>Check if there has been any error while calling the various
functions (at least for <tt class="literal">scanf</tt>, <tt class=
"literal">pow</tt> and <tt class="literal">sqrt</tt>.) For example,
while calling the <tt class="literal">pow</tt> function, it is
possible that an overflow occurred. This can be determined by
checking the <tt class="literal">errno</tt> variable. Such
validations would help to determine the precise cause of a
failure.</p>
<p>Also note that <tt class="literal">scanf</tt> doesn't provide
much error checking. For example, if a value overflows, <tt class=
"literal">scanf</tt> doesn't report it. For this reason, a
combination of <tt class="literal">fgets</tt> and <tt class=
"literal">strtod</tt> is preferred. The <tt class=
"literal">strtod</tt> function returns the error status through the
<tt class="literal">errno</tt> variable.</p>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>The format
specifier in scanf</h5>
</div>
<p>For a <span class="type">double</span>, <tt class=
"literal">scanf</tt> requires that <tt class="literal">%lf</tt> be
specified as the format. [2]</p>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3>Linker
Error</h5>
</div>
<p>Including a header file doesn't &quot;define&quot; the functions of a
library. They just declare them. The function definitions of a
library are probably available elsewhere in the system as
shared/static libraries. This information should be provided to the
compiler (or more precisely, to the linker). Normally the option is
'-l' (l as in Link). For more details on this, look at the
compiler/linker documentation and man pages.</p>
</div>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3>
</div>
<p>[1] <a href="http://www.eskimo.com/~scs/C-faq/q6.2.html" target=
"_top">http://www.eskimo.com/~scs/C-faq/q6.2.html</a></p>
<p>[2] <a href="http://www.eskimo.com/~scs/C-faq/q12.13.html"
target="_top">http://www.eskimo.com/~scs/C-faq/q12.13.html</a></p>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3>From ??
[<i><span class="remark">see my comment earlier</span></i>]</h3>
</div>
<p>I'll first answer the main concern of the student, and then
address some other issues. Certainly, there's a misunderstanding
about arrays and pointers. The first definition <tt class=
"literal">int a[10];</tt> creates an array of ten <span class=
"type">int</span>s, that is, it reserves space somewhere for ten
consecutive <span class="type">int</span>s. That 'somewhere' can be
identified as <tt class="varname">a</tt>. On the other hand,
<tt class="literal">int *p = (int *) malloc(10);</tt> creates a
pointer to an <span class="type">int</span>, named p. Where does it
point? To the memory location [for a block of ten <span class=
"type">unsigned char</span>] returned by <tt class=
"literal">malloc()</tt>, or to <tt class="literal">NULL</tt>, in
case the request couldn't have been granted. So now let's tackle
the size issue: <tt class="literal">sizeof()</tt> is an operator
which returns the number of bytes of an expression or a type passed
as argument. So if <tt class="literal">sizeof(int)</tt> is 4 in
your environment (which happens to be a common size on most 32-bit
architectures) then <tt class="literal">sizeof(a)</tt> will be 40
(10 integers each occupying 4 bytes) In the second case, you get
the size of a pointer to <span class="type">int</span>, which in
your system turns out to be 4 bytes.</p>
<p>Now with this information in hand, we have a better
understanding to answer to your questions:</p>
<div class="variablelist">
<dl>
<dt><span class="term">Q:</span></dt>
<dd>
<p>&quot;My understanding says even array name is a pointer. If so why
it does not show <tt class="literal">sizeof(a)</tt> as 4?&quot;</p>
</dd>
<dt><span class="term">A:</span></dt>
<dd>
<p>Because an array is not a pointer! In many cases, its name is
converted to a pointer to the first element (this is generally
called decay), but the object itself remains being an array! The
only exceptions when this decay doesn't take place are when being
an operand of the sizeof operator (which is our case), the &amp;
unary operator (address operator).</p>
</dd>
<dt><span class="term">Q:</span></dt>
<dd>
<p>&quot;Or if <tt class="literal">sizeof</tt> shows the total allocated
memory then why <tt class="literal">sizeof(p)</tt> does not show
10?&quot;</p>
</dd>
<dt><span class="term">A:</span></dt>
<dd>
<p>Because <tt class="literal">sizeof</tt> just returns the size in
bytes of the operand passed, in this case an identifier for a
pointer to <span class="type">int</span>.</p>
</dd>
</dl>
</div>
<p>Now let's see briefly a couple of errors in your code. Let's see
<tt class="literal">malloc()</tt> usage. First of all, the cast is
unnecessary, since a <span class="type">void*</span> is
automatically converted to any other pointer type. That alone isn't
a big issue by itself, but your code shows a good reason not to do
it: you forgot <tt class="literal">#include &lt;stdlib.h&gt;</tt>
which is where <tt class="literal">malloc()</tt> prototype is
declared, thus letting the compiler assume the function returns an
<span class="type">int</span>. With this assumption, assigning the
<span class="type">int</span> returned by <tt class=
"literal">malloc()</tt> to the pointer to <span class=
"type">int</span>, would cause a diagnostic unless you force the
conversion, which is done by a cast, which is exactly what you're
doing. See how this innocent-looking cast turns out to hide a
potential bug in your program. So the advice here is not to cast
but <tt class="literal">#include</tt> the appropriate header.</p>
<p>Another error is the omission of a return-statement, given that
<tt class="function">main()</tt> must return an <span class=
"type">int</span>, as your definition clearly states.</p>
<p>The last error has to do with the data type used to represent
the size of an object. <tt class="varname">sizeofyields</tt> a
<tt class="literal">size_t</tt> value, which is a <tt class=
"literal">typedef</tt> to a basic type, such as <span class=
"type">unsigned int</span> or <span class="type">unsigned long
int</span>. So what specifier (<tt class="literal">%u</tt>,
<tt class="literal">%lu</tt>) should we use? Well, it depends on
the system you're working on, depending on <tt class=
"literal">sizeof</tt> definition (check <tt class=
"literal">stddef.h</tt>) On the other hand, in C99 you can use
<tt class="literal">%z</tt> for <tt class="literal">size_t</tt>,
thus avoiding the above mess. Lastly, I suppose your intention is
allocating space for 10 integers, so if that were the case, you
should do:</p>
<pre class="programlisting">
int *p = malloc(10 * sizeof(int));
</pre>
<p>or</p>
<pre class="programlisting">
int *p = malloc(10 * sizeof *p);
</pre>
<p>that is, reserve space for 10 objects of the type pointed by
<tt class="varname">p</tt>, which in this case is an <span class=
"type">int</span>. Note that even though both statements are valid,
the second one is preferred, because the data type is not fixed,
but expressed by the content of the pointer. So if you later happen
to change of pointer type, you won't run into any problem.</p>
<p>So our program would look like this:</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

int main() {
  int a[10];
  int *p = malloc(10 * sizeof *p);
  printf(&quot;Size of a = %lu\n&quot;, sizeof a);
  printf(&quot;Size of p = %lu\n&quot;, sizeof p);
  return 0;
}
</pre>
<p>Note that <tt class="literal">sizeof</tt>'s operand doesn't need
to be put inside parentheses, when it isn't a data type.</p>
<p>Now I'll show you the same code in C++, and briefly discuss some
useful facilities the language provides us.</p>
<pre class="programlisting">
#include &lt;iostream&gt;
using std::cout;

int main() {
  int a[10];
  int *p = new int[10];
  cout &lt;&lt; &quot;Size of a = &quot; &lt;&lt; sizeof a &lt;&lt; '\n';
  cout &lt;&lt; &quot;Size of p = &quot; &lt;&lt; sizeof p &lt;&lt; '\n';
}
</pre>
<p>The two most important differences relate to memory allocation
and printing output to <tt class="literal">stdout</tt>. First note
that using <tt class="literal">new</tt>, you don't have to think in
terms of raw bytes as you do with <tt class=
"literal">malloc()</tt>. You just ask memory for n objects of type
<span class="type">T</span>. Also note that you don't need to use
bizarre specifiers such as <tt class="literal">%d</tt>, <tt class=
"literal">%u</tt>, etc., you just specify what you want to output
and there you go. One minor detail here is that the compiler
inserts automatically a '<tt class="literal">return 0</tt>' if you
don't provide it, but note that this is done only in <tt class=
"function">main()</tt>.</p>
<p>[<i><span class="remark">However note that this program, like
the C one, forgets to release the memory obtained
dynamically.</span></i>]</p>
<div class="sect3" lang="en">
<div class="titlepage">
<h3>
</div>
<p>This problem has to do with misuse of conversion specifiers.
Unfortunately, the same specifier (<tt class="literal">%f</tt>)
means different things in these two generally interrelated
functions. In the case of <tt class="literal">printf(),</tt>
'<tt class="literal">%f</tt>' specifies a <span class=
"type">double</span> argument, and applying the length modifier
'<tt class="literal">l</tt>' doesn't affect its meaning at all. So
in our case, using '<tt class="literal">%f</tt>' or '<tt class=
"literal">%lf</tt>' hold the same meaning [*] So what if you want
to print a single precision floating point number? (a <span class=
"type">float</span>, to be precise). You have no other choice other
than using <tt class="literal">%f</tt>! The key issue here is
automatic conversion: when you pass a float to <tt class=
"literal">printf()</tt> (and to any variadic function, the compiler
automatically promotes it to a <span class="type">double</span>.
Thus <tt class="literal">printf()</tt> always receives <span class=
"type">double</span>s! Note there isn't any problem with this, as
we're not losing precision. But in the case of <tt class=
"literal">scanf()</tt>, '<tt class="literal">%f</tt>' and
'<tt class="literal">%lf</tt>' are two different things. In the
first case you ask for a <span class="type">float</span>, in the
second for a <span class="type">double</span>. Why the distinction
here? Because <tt class="literal">scanf()</tt> arguments are
pointers, which are not promoted.</p>
<p>This is also a good occasion to point out a better way to
receive input from a user. Actually, <tt class=
"literal">scanf()</tt> is targeted to read formatted input (for
example, from a configuration file, table, etc) rather than from an
unforeseeable input source as a human being. The problem with
<tt class="literal">scanf()</tt> relates to its poor support of
error detection, among other things. Instead you should use
something like the <tt class="literal">fgets()</tt> and <tt class=
"literal">strtod()</tt> in combination:</p>
<pre class="programlisting">
fgets(buffer, sizeof buffer, stdin);
strtod(buffer, NULL);
</pre>
<p>You should also add some error checking to make sure you get
what you're expecting. <tt class="literal">fgets()</tt> makes it
easy; returning a NULL pointer in case of error. <tt class=
"literal">strtod()</tt> is a little more complicated, because it
returns you the value parsed, or 0 if there was any problem. But as
you might have already guessed, 0 is also a valid value! So to set
apart an error from a legitimate input, <tt class=
"literal">strtod()</tt> makes use of the infamous <tt class=
"literal">errno</tt>. Fortunately for us, we won't deal with that
mess. In our problem domain, we're dealing with sides of a
triangle, which means that positive values are the only valid
values we're looking for! [<i><span class="remark">What about
degenerate triangles?</span></i>]</p>
<p>This simplifies a lot our function, at the expense of getting
more detailed error messages:</p>
<pre class="programlisting">
double read_side(void) {
  char buf[32];
  if(fgets(buf, sizeof buf, stdin) != NULL)
    return strtod(buf, NULL);
  else
    return 0;
}
</pre>
<p>Now let's see some other problems, in a 'top to bottom'
approach:</p>
<pre class="programlisting">
// Define Libraries
#include &lt;stdio.h&gt;
#include &lt;math.h&gt;
</pre>
<p>This is wrong. You're not defining any libraries at all. You're
simply including declarations to be used by your program.</p>
<pre class="programlisting">
main() {
</pre>
<p><tt class="function">main()</tt> returns an <span class=
"type">int</span> by definition, so you should state <tt class=
"literal">int main()</tt> instead, and place the corresponding
<tt class="literal">return 0</tt> at the end of the function.</p>
<pre class="programlisting">
printf(&quot;Enter base:&quot;);
scanf(&quot;%f&quot;, &amp;base);
</pre>
<p>You need to add <tt class="literal">fflush(stdout)</tt> to
ensure text is displayed before the <tt class=
"literal">scanf()</tt>. [<i><span class="remark">I cannot remember
ever finding that necessary.</span></i>]</p>
<pre class="programlisting">
printf(&quot;hypotenuse is %f&quot;, &amp;hypotenuse);
</pre>
<p>You're passing the address of a <span class="type">float</span>
variable to <tt class="literal">printf()</tt>, instead of the value
expected. Besides, the identifier you're passing doesn't even
exist. In case you meant <tt class="varname">hypo</tt>, you should
pass the object itself, not its address, to comply the requirement
imposed by the <tt class="literal">%f</tt> specifier. You should
also add <tt class="literal">fflush(stdout)</tt>, or suffix a
<tt class="literal">\n</tt> to ensure the string is flushed.
[<i><span class="remark">They do entirely different things, the
first forcibly flushes <tt class="literal">stdout</tt> the second
appends a new-line to the output buffer.</span></i> ]</p>
<p>Lastly, not an error but a better practice. In this case, it's
better to manually square the numbers you received, that is, use
something like <tt class="function">sqrt(base * base, height *
height);</tt> which will surely give you better performance.</p>
<p>This is how a possible implementation might look like:</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;math.h&gt;

double read_side(void) {
  char buf[32];
  if(fgets(buf, sizeof buf, stdin) != NULL)
    return strtod(buf, NULL);
  else return 0;
}

int main(void) {
  double hypo, base, height;
/* Enter base and height */
  printf(&quot;Enter base: &quot;);
  fflush(stdout);
  base = read_side();
  printf(&quot;Enter height: &quot;);
  fflush(stdout);
  height = read_side();
  if(base &gt; 0 &amp;&amp; height &gt; 0) {
    hypo = sqrt(base*base + height*height);
    printf(&quot;Hypotenuse is %f\n&quot;, hypo);
    return EXIT_SUCCESS;
  }
  else {
    fprintf(stderr,
        &quot;Both sides must be positive\n&quot;);
    return EXIT_FAILURE;
  }
}
</pre>
<p>[*] This only applies to C99. In C89, the behaviour is
undefined, so we'd better use <tt class="literal">%f</tt> for
maximum compatibility.</p>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3>From Catriona
O'Connell <tt class="email">&lt;<a href=
"mailto:catriona38@hotmail.com">catriona38@hotmail.com</a>&gt;</tt></h3>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3>
</div>
<p>The program needs to include <tt class="literal">stdlib.h</tt>
for the declaration of <tt class="literal">malloc()</tt>. Without
this declaration it is assumed to return an <span class=
"type">int</span> rather than a pointer to <span class=
"type">void</span>.</p>
<p>If the student is trying to dynamically allocate the same amount
of storage as a ten element array, then he/she should replace the
argument 10 in the call to <tt class="literal">malloc()</tt> with
<tt class="literal">10 * sizeof(int)</tt>.</p>
<p>The cast to <tt class="literal">(int *)</tt> of the return type
from the call to <tt class="literal">malloc</tt> is not required
since the coercion of <tt class="literal">(void *)</tt> to
<tt class="literal">anytype *</tt> is automatic. It may be harmful
to do so if <tt class="literal">malloc()</tt> is not declared to
return <span class="type">void*</span>, as in this case because of
the missing header file. The explicit case was necessary in
pre-ANSI C and is still necessary in C++. In the case here, the
cast may be erroneous because only 10 bytes have been allocated.
Minor stylistic point: No check is made on the return code of
<tt class="literal">malloc()</tt>. <tt class=
"literal">malloc()</tt> returns <tt class="literal">NULL</tt> if
the memory cannot be allocated. In production code this should be
checked.</p>
<p>The function <tt class="literal">sizeof()</tt> [<i><span class=
"remark">actually it is an operator not a function</span></i>]
produces an <span class="type">unsigned integer</span> object of
type <span class="type">size_t</span> (declared in <tt class=
"filename">stddef.h</tt> or <tt class="filename">cstddef</tt> for
C++). This header should be included for completeness.</p>
<p>The C Standard (ISO/IEC 9899:1999(E)) states in 6.5.3.4/3</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;When applied to an operand that has type <span class=
"type">char</span>, <span class="type">unsigned char</span>, or
<span class="type">signed char</span>, (or a qualified version
thereof) the result is 1. When applied to an operand that has array
type, the result is the total number of bytes in the array. When
applied to an operand that has structure or union type, the result
is the total number of bytes in such an object, including internal
and trailing padding.&quot;</p>
</blockquote>
</div>
<p>The C Standard (ISO/IEC 9899:1999(E)) states in 6.3.2.1/3</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;Except when it is the operand of the <tt class=
"literal">sizeof</tt> operator or the unary <tt class=
"literal">&amp;</tt> operator, or is a string literal used to
initialize an array, an expression that has type ''array of type''
is converted to an expression with type ''pointer to type'' that
points to the initial element of the array object and is not an
lvalue. If the array object has register storage class, the
behavior is undefined.&quot;</p>
</blockquote>
</div>
<p>In this case the student is asking for the size of the array
&quot;<tt class="varname">a</tt>&quot; (40 bytes) and the pointer <tt class=
"varname">p</tt> (4 bytes) - not the size of the object to which
<tt class="varname">p</tt> points. The program is therefore
reporting the correct values.</p>
<p>The C++ Standards (ISO/IEC 14882:1998(E)) states in 5.3.3/2</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;When applied to a reference or a reference type, the result is
the size of the referenced type. When applied to a class, the
result is the number of bytes in an object of that class including
any padding required for placing objects of that type in an array.
The size of a most derived class shall be greater than zero (1.8).
The result of applying sizeof to a base class subobject is the size
of the base class type.) When applied to an array, the result is
the total number of bytes in the array. This implies that the size
of an array of n elements is n times the size of an element.&quot;</p>
</blockquote>
</div>
<p>You have to be careful about using <tt class=
"literal">sizeof</tt> with arrays. You have to be sure that you use
it only at a point in the program where you are dealing with the
actual array and not a pointer to its first element. In many, but
not all, contexts an array <tt class="literal">T a[N]</tt> will
implicitly convert to a pointer to its first element <tt class=
"literal">T *p = a</tt>. This is not the same as saying that an
array is a pointer.</p>
<p>In C++PL (Special Edition) B.2.1 Bjarne Stroustrup notes that in
C the <tt class="literal">sizeof</tt> a character constant and of
an enumeration equals <tt class="literal">sizeof(int)</tt>. In C++,
<tt class="literal">sizeof('a')</tt> equals <tt class=
"literal">sizeof(char)</tt> and a C++ implementation is allowed to
choose whatever size is most appropriate for an enumeration.</p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3>
</div>
<p>The final <tt class="literal">printf()</tt> should refer to
<tt class="varname">hypo</tt> not <tt class=
"varname">&amp;hypotenuse</tt> (the address of a non-existent
variable).</p>
<p>There is a missing return in <tt class=
"function">main()</tt>.</p>
<p>The function <tt class="literal">scanf()</tt> can return a
<span class="type">double</span> into its argument, but the format
flag should have been specified as <tt class="literal">%lf</tt>. By
specifying a <span class="type">float</span>, the results will be
unpredictable.</p>
<p><tt class="literal">scanf()</tt> is evil. As pointed out in the
responses to SCC21, calling <tt class="literal">scanf()</tt>
multiple times in the same module can lead to excess characters
being left in the input buffer. Everything after the valid number
(including the crlf) is left in the buffer. The second call to
<tt class="literal">scanf()</tt> tries to interpret that according
to the input format. The student would either have to program in
assignment to a string for the remainder of the buffer or be
introduced to the delights of non-assigning <tt class=
"literal">scanf()</tt> calls such as</p>
<pre class="programlisting">
scanf(&quot;%*[^\n]&quot;); // skip to end of line.
scanf(&quot;%*1[\n]&quot;); // skip a newline character.
</pre>
<p>to clear the input buffer.</p>
<p>If the student is determined to use <tt class=
"literal">scanf()</tt> then he/she should have checked the return
code which specifies how many variables have been assigned.</p>
<p>The call to <tt class="literal">pow()</tt> to create a square is
overkill and can be replaced by simple multiplication.</p>
<p>The attached code sample is a minimally improved version using
nonassigning <tt class="literal">scanf()</tt> calls and another
with the data gathering moved to a separate function.</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;
#include &lt;math.h&gt;
#define BUF_SIZE 100
double getDouble(char * prompt);

int main() {
  double hypo, base, height;
  base = getDouble(&quot;Enter base&quot;);
  height = getDouble(&quot;Enter height&quot;);
  hypo = sqrt(base*base + height*height);
  printf(&quot;hypotenuse is %lf&quot;, hypo);
  return 0;
}

double getDouble(char * prompt) {
  double num;
  char buffer[BUF_SIZE];
  int gotDouble = 0;
  while(!gotDouble) {
    printf(&quot;%s :&quot;, prompt);
    if(fgets(buffer, BUF_SIZE, stdin)) {
      if(sscanf(buffer, &quot;%lf&quot;, &amp;num) == 1) {
        gotDouble = 1;
      }
      else {
        printf(&quot;Error in sscanf()\n&quot;);
      }
    }
    else printf(&quot;Error in fgets()\n&quot;);
  }
  return num;
}
</pre></div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2>The Winner
of SCC 25</h2>
</div>
<p>The editor's choice is: <span class="bold"><b>Annamalai
Gurusami</b></span></p>
<p>Please email <tt class="email">&lt;<a href=
"mailto:francis@robinton.demon.co.uk">francis@robinton.demon.co.uk</a>&gt;</tt>
to arrange for your prize.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2>Student
Code Critique 26</h2>
</div>
<p>(Submissions to <tt class="email">&lt;<a href=
"mailto:francis@robinton.demon.co.uk">francis@robinton.demon.co.uk</a>&gt;</tt>
by March 10th)</p>
<p>It is generally worth sending in a late entry, depending on my
work load it may or may not be considered for the prize but it will
eventually get published. However this time please make an extra
effort to get entries in on time as I would like to get this column
done before the ECMA TG5 (C++/CLI binding) in Melbourne.</p>
<p>This time the problem is still about some student code however
it is code that works but how do you help the student to move
forward? Yes, I know the simple answer but I am looking for
something more.</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>The following program (below my question) produces the results I
want, but I am trying to create a for-loop to replace all of the
cout statements.</p>
<p>What I have so far is:</p>
<pre class="programlisting">
for(int i = 0; i &lt;= len; i++)
  cout &lt;&lt; str[i + 1];
</pre>
<p>This will produce: &quot;eed help with C++.&quot;</p>
<p>Could someone clue me in on how to create the <tt class=
"literal">for</tt>-loop? Should I be using a nested for loop? Any
help would be appreciated.</p>
</blockquote>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3>Student's
Program:</h3>
</div>
<pre class="programlisting">
#include&lt;iostream&gt;
#include&lt;cstring&gt;

using namespace std;

void main (){
  const int arraySize = 20;
  char str[arraySize] = &quot;Need help with C++.&quot;;
  int len = strlen(str);
  cout &lt;&lt; &quot;The sentence \&quot;Need
           help with C++.\&quot; has &quot;
       &lt;&lt; len &lt;&lt; &quot; characters.&quot;
       &lt;&lt; endl &lt;&lt; endl;
  cout &lt;&lt; str &lt;&lt; endl;
  cout &lt;&lt; str + 1 &lt;&lt; endl;
  cout &lt;&lt; str + 2 &lt;&lt; endl;
  cout &lt;&lt; str + 3 &lt;&lt; endl;
  // 13 similar statements snipped
  cout &lt;&lt; str + 16 &lt;&lt; endl;
  cout &lt;&lt; str + 17 &lt;&lt; endl;
  cout &lt;&lt; str + 18 &lt;&lt; endl;
}
</pre></div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
