    <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  :: Questions &amp; Answers</title>
        <link>https://members.accu.org/index.php/articles/937</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 + CVu Journal Vol 11, #6 - Oct 1999</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/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/c129/">116</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+129/">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;Questions &amp; Answers</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 October 1999 13:15:34 +01:00 or Sun, 03 October 1999 13:15:34 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
</div>
<p>I have decided to change the organisation of this column. Each
issue I will publish a number of questions that have been raised
either directly with me or through newsgroups, email lists etc. and
invite readers to give their best shot at answering the problem.
Hopefully many of you will want to participate. I do not promise to
print all responses but I will arrange that everything that does
not embarrass the author will either be printed or displayed on our
web site. I have no doubt that the process of understanding other
people's problems is very instructive.</p>
<p>I will provide a column of this style for both C Vu and Overload
(though the questions and answers will require more technical skill
for the latter).</p>
<p>Here are a few to get you started. Note that some questions have
first order simple answers (i.e. you cannot do that &hellip; but I
have tried to select problems because they have more hidden beneath
the surface.</p>
<p><span class="bold"><b>Question 1:</b></span></p>
<p>What is the best way of converting from strings to enums? I
would like a solution that ensures that when a new enum is added, a
corresponding string must also be added to ensure consistency.</p>
<p>I have seen two ways to do this but each have their problems</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>ensures that all possible strings are checked but enumeration
values must be sequential</p>
</li>
<li>
<p>enums don't need to be sequential but if an extra value is added
the programmer must add an extra if statemen</p>
</li>
</ul>
</div>
<pre class="programlisting">
enum MyEnum { eOne, eTwo, ..... eEnd, eStart=eOne, eInvalid=eEnd};
string MyEnumStrings[eEnd] = { &quot;One&quot;, &quot;Two&quot;, ....};
//Method 1
MyEnum StringToEnum(string TheString){
  for (MyEnum e=eStart; e&lt;eEnd ; e=MyEnum(e+1))
   if (TheString == MyEnumStrings[e])
     return e;
  return eInvalid;
}
//Method 2
MyEnum StringToEnum(string TheString){
  if (TheString == MyEnumStrings[eOne]) return eOne; 
  if (TheString == MyEnumStrings[eTwo]) return eTwo;
  //.... etc
}
</pre>
<p><span class="bold"><b>Question 2</b></span></p>
<p>How do I output a float with exactly 'n' decimal places in
C++?</p>
<p><span class="bold"><b>Question 3</b></span></p>
<p>I found the following code fragment for implementing unary
minus:</p>
<pre class="programlisting">
class Complex {
   double re, im
   // ...
public:
   // ...
   Complex operator-() const { return Complex(-re, -im); }
   // ...
};
</pre>
<p>I don't understand what the const is doing in the middle. I
thought const was for variables.</p>
<p><span class="bold"><b>Question 4</b></span></p>
<p>I want to use a dynamically created m by n matrix, but it seems
that no variable can handle <tt class="literal">new
double[m][n]</tt> properly unless n is predefined. I was told that
there's no way to use</p>
<pre class="programlisting">
new double[m][n]
</pre>
<p>where m and n are <tt class="type">int</tt> variables. So what
should I do?</p>
<p><span class="bold"><b>Question 5</b></span></p>
<p>I have the following problem with my program wherein I am using
STL vectors to store documents. I store each document in a vector
with each element containing a line. (I am using gcc 2.8 under
Solaris 2.6).</p>
<p>I have a calling code like:</p>
<pre class="programlisting">
main () {
    vector&lt;string&gt;* doc;
    Break(doc);
    return 0;
}
</pre>
<p>My implementation of the <tt class="methodname">Break</tt>
method goes as follows:</p>
<pre class="programlisting">
void Break (const vector&lt;string&gt;* doc) {
    vector&lt;string&gt;::iterator i;
    char* line;
    for (i=doc-&gt;begin(); i != doc-&gt;end(); i++) {
        strcpy(line, (*i).c_str());  // copy to remove const of (*i).c_str()
        while (*line != '\0') { cout &lt;&lt; *line &lt;&lt; &quot; &quot;; ++line; }
        cout &lt;&lt; endl;
    }
}
</pre>
<p>In the above program, the for loop traverses only a portion of
the vector elements (13 lines) and aborts with a &quot;Segmentation
fault (core dump)&quot; error or at times with a &quot;Bus error (Core dump)&quot;
error messages. When I replace the while loop with</p>
<pre class="programlisting">
cout  &lt;&lt; line &lt;&lt; endl;
</pre>
<p>it works perfectly (sends all the elements of the vector to
<tt class="classname">stdout</tt>). What is happening?</p>
<p><span class="bold"><b>Question 6</b></span></p>
<p>I have a problem that I'm confused about: I want a function to
return an array (ptr?) such that <tt class="literal">int a[4] =
return_int();</tt> This codes doesn't work.... B is where I want to
set <tt class="literal">i[4] = g[4];</tt></p>
<pre class="programlisting">
int g[4];
int main (int argv, char **argc) {
         g[0] = 1; g[1] = 2; g[2]=3; g[3]=4;
         test1();
         return 0;
}
void test1() {
         int i[4];          i = return_int();               /* B */
}
 int *return_int() {      /* return int*?? */  return g;     /* not sure here */  }
</pre>
<p><span class="bold"><b>Question 7</b></span></p>
<p>I recently had to extract the day, month and year values from a
32-bit number, which was defined as &quot;the number of seconds elapsed
since midnight (00:00:00), January 1, 1970, Universal Co-ordinated
Time.&quot; The only way I could think to do it was via repeated
subtraction, which worked OK but didn't feel right. I'm sure is
there is a better way. I then had to do a similar thing with a
64-bit number, for which I didn't have a definition, but I did know
that the value 0x42C9D10443A00000 represented 1 January 1800. Any
ideas?</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e115" id="d0e115"></a>From:
&quot;billcartwright&quot; <tt class="email">&lt;<a href=
"mailto:billcartwright@ouvip.com">billcartwright@ouvip.com</a>&gt;</tt></h2>
</div>
<p>As I have a copy of MS Fortran Professional, which includes ISML
libraries, and Visual C++ I experimented with calling the Fortran
libraries from Visual C++ with some unexpected results, to me if
not others. I believed that, if I declared an array as <tt class=
"literal">double a[2][3]</tt>, I could then refer to it using
'<tt class="varname">a</tt>' as a pointer. This appears to agree
with all references I can find and with the ISML article which
defines '<tt class="varname">a</tt>' as above then calls a
transpose routine as follows:</p>
<pre class="programlisting">
DTRNRR(&amp;nra, &amp;nca, a, &amp;lda, &amp;nrb, &amp;ncb, b, &amp;ldb);
</pre>
<p>The C header file shows:</p>
<pre class="programlisting">
void _stdcall DTRNRR(long*, long*, double*, long*, long*, long*, double*, long*);
</pre>
<p>However in Visual C++ 6.0 I received the error message:</p>
<pre class="screen">
C2664: 'DTRNRR' : cannot convert parameter 3 from 'double [2][3]' to 'double *'
</pre>
<p>Following up on Error C2664 did not help me.</p>
<p>I then redefined '<tt class="varname">a</tt>' as <tt class=
"literal">double *a</tt> and used <tt class="literal">a =
&amp;aMatrix[0][0];</tt> to get a pointer for use in the routine
this seems to work fine but does not line up with my previous
understanding of pointers and arrays.</p>
<p>As a further check I tried:</p>
<pre class="programlisting">
for(p = aMatrix; p != aMatrix + 6; p++)
  cout &lt;&lt; *p &lt;&lt; &quot; &quot;  &lt;&lt; endl;
</pre>
<p>This gave the same error message until modified to:</p>
<pre class="programlisting">
for(p = &amp;aMatrix[0][0]; p != &amp;aMatrix[0][0] + 6; p++)
  cout &lt;&lt; *p &lt;&lt; &quot; &quot;  &lt;&lt; endl;
</pre>
<p>Checking that <tt class="varname">aMatrix</tt> and <tt class=
"literal">&amp;aMatrix[0][0]</tt> are the same using:</p>
<pre class="programlisting">
cout &lt;&lt; &quot;a:              &quot; &lt;&lt; a &lt;&lt; &quot;\n&quot;;
 cout &lt;&lt; &quot;aMatrix:        &quot; &lt;&lt; aMatrix &lt;&lt; &quot;\n&quot;;
 cout &lt;&lt; &quot;&amp;aMatrix[0][0]: &quot; &lt;&lt; &amp;aMatrix[0][0] &lt;&lt; &quot;\n&quot;;
 cout &lt;&lt; endl;
</pre>
<p>on my machine gives:</p>
<pre class="screen">
a:   004350C0
aMatrix:   004350C0
&amp;aMatrix[0][0]: 004350C0
</pre>
<p>i.e. the same result for <tt class="varname">a</tt>, <tt class=
"varname">aMatrix</tt> and <tt class=
"literal">&amp;aMatrix[0][0]</tt>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e187" id="d0e187"></a>Answer from
Francis Glassborow</h2>
</div>
<p>Bill's problem is that he (along with many others) has not taken
the type of the pointer into account. Having the same value is not
the same as being the same thing &#9786; Let me see if I can
clarify.</p>
<p>If you simply use the name of an array in a context where a
pointer is required you will get a pointer to the first element of
the array. So if</p>
<pre class="programlisting">
char message[] = &quot;Help&quot;;
</pre>
<p>the type of the address that results from using message is
'<tt class="type">char*</tt>' and its value is the address (pointer
constant) to the first byte of the array of five (do not forget the
string terminator) <tt class="type">char</tt>s created to store a
modifiable copy of &quot;Help&quot;</p>
<p>This is as far as many programmers get. However the next element
is that C and C++ only support one dimensional arrays. They fudge
multi-dimensional arrays by having arrays of arrays&hellip; (or
dynamically by having arrays of pointers, but that is another level
of complexity). When you write:</p>
<pre class="programlisting">
int matrix[2][3];
</pre>
<p>you are declaring <tt class="varname">matrix</tt> to be an array
of 2 &lt;arrays of three <tt class="type">int</tt>&gt;. What is the
first element of <tt class="varname">matrix</tt>? It is an array of
three <tt class="type">int</tt>. So the type of the pointer you get
from using <tt class="varname">matrix</tt> is pointer to array of
three int (and while we are on this subject, that inner array does
generally not decay to a pointer to <tt class="type">int</tt> -
again a complication that I will leave for now, but it matters when
you try to write functions that have a multi-dimensional
parameter)</p>
<p>The type of <tt class="varname">matrix</tt> decays to <tt class=
"type">*(int [3])</tt>. Now the prototype DTRNRR is possibly wrong
because I think some of the pointers should be pointing to rows
(arrays of <tt class="type">double</tt>) , however all the
programmer wanted was the values, type safety would be handled by
careful programming. Making the calls work seems to be a matter of
using casts with the utmost care. Again, I am going to side-step
the issue because you have to work with the prototype provided but
I suspect that the programmer of the library did not understand
arrays in C as well as we might wish.</p>
<p>Now let me look at getting the start address of the array in the
way in which you wanted it. What is the first element of <tt class=
"varname">matrix</tt>? <tt class="literal">matrix[0]</tt> which is
an array of 3 <tt class="type">int</tt>s. Subtler, when I write
<tt class="literal">matrix[0]</tt> I name an array and we know that
in correct context this decays to a pointer to the first element of
the array. What is the first element of <tt class=
"literal">matrix[0]</tt>? It is the int found at <tt class=
"literal">matrix[0][0]</tt>. So the solution to your original
problem was to use <tt class="literal">a[0]</tt> instead of
<tt class="varname">a</tt>.</p>
<p>Sorry if this is still not clear, pointers give almost all of us
headaches.</p>
<p>In general to get a pointer of the type of a single element of a
multi-dimensional array you must provide for all the dimensions but
the last one.</p>
<p>You could have written your for loop as:</p>
<pre class="programlisting">
for(p = aMatrix[0]; p != aMatrix[0]+ 6; ++p)   cout &lt;&lt; *p &lt;&lt; &quot; &quot;  &lt;&lt; endl;
</pre></div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
