Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>sizeof</code> operator statically evaluates to the size of the thing you are passing to it. A <code>char*</code> is a pointer which, depending on the machine architecture has a specific size (4 bytes on 32 bit systems and 8 bytes on 64 bit machines). To accomplish what you are trying to do, I suggest you use the <code>string</code> type which you can use by adding <code>#include &lt;string&gt;</code> along with <code>using namespace std;</code> to your source file.</p> <pre><code>string line; cin &gt;&gt; line; cout &lt;&lt; line.length() &lt;&lt; endl; </code></pre> <p>It's less error prone and easier to use.</p> <p>By the way, the thing you've tried to do is really dangerous. In fact, when you use <code>cin &gt;&gt; myArray</code>, you should have already allocated some memory for <code>myArray</code> which you haven't done. This will cause memory corruption which might crash your program and possibly put it to buffer overrun attacks.</p> <p>A simple array in C++ has no idea about its size. You can use <code>sizeof</code> <b>only if the array is statically allocated</b> and you are using <code>sizeof</code> on the array itself, not another pointer to it, for example this won't work as you might expect:</p> <pre><code>int x[5]; int *a = &amp;x[0]; // a[i] is now the same as x[i] but: cout &lt;&lt; sizeof(x) &lt;&lt; endl; // prints 20, assuming int is 32 bits long cout &lt;&lt; sizeof(a) &lt;&lt; endl; // prints 4, assuming a pointer is 32 bits long </code></pre> <p>Note that the total size of the array is printed on the first line, not the element count. You can use <code>sizeof(x)/sizeof(*x)</code> to find out element count in static arrays. This thing is not possible for dynamically allocated arrays using <code>new</code>. In fact C++ arrays are very error prone and you should take extreme care when working with them and you'd better use <code>vector</code> and <code>string</code> in most cases instead.</p>
 

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