Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Firstly, am I right in assuming that this is a learning exercise for you in learning "how to create your own string class"? C++ has already got a built-in <em>string</em> type which you should always prefer for the most part.</p> <p>the <code>sizeof</code> operator yields the size (in bytes) of its operand, which in this case is <strong>c</strong> whose type is <code>char*</code> - it looks like what you're actually after is the length of a null-terminated character array (a "C" string") - you're already using <em>strlen</em>, so I'd suggest you simply want to use that again. (taking a null-terminator into account too)</p> <pre><code>name = resize(name, l, strlen(c) + 1); </code></pre> <p>Note, that your code looks as if it suffers from memory leaks. You're assigning a new value to your <em>name</em> variable without clearing up whatever existed there first.</p> <pre><code>if(l &lt; strlen(c)+strlen(name)) { char* my_new_string = resize(name, l, strlen(c)); if( my_new_string != NULL ) { delete [] name; name = my_new_string; } } </code></pre> <p><em>EDIT</em>: As other replies have pointed out, there's still plenty wrong with the code which could be resolved using C++'s <code>string</code> and <code>vector</code>. </p> <p>Here's one possible way you could implement add_chars</p> <pre><code>void MyString::add_chars(char* c) { if( c != NULL &amp;&amp; name != NULL ) { size_t newlength = strlen(c) + strlen(name) + 1; char* newstring = new char[newlength]; if( newstring != NULL ) { size_t namelength = strlen(name); size_t remaining = newlength - namelength; strncpy( newstring, name, newlength ); strncpy( &amp;newstring[namelength] , c, remaining ); delete [] name; name = newstring; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload