Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You are confusing several things.</p> <blockquote> <p>strtok takes in arguments (char*, const char*)....name is an array and hence a pointer to its first element...</p> </blockquote> <p><code>name</code> is an array, and <strong><em>it's not</em></strong> a pointer to its first element. An array <em>decays</em> in a pointer to its first argument in several contexts, but in principle it's a completely different thing. You notice this e.g. when you apply the <code>sizeof</code> operator on a pointer and on an array: on an array you get the array size (i.e. the cumulative size of its elements), on a pointer you get the size of a pointer (which is fixed).</p> <blockquote> <p>but if we made a declaration like string name="avinash" and passed name as argument then the prog doesnt work but it should because name of string is a pointer to its first character...</p> </blockquote> <p>If you make a declaration like</p> <pre><code>string name="avinash"; </code></pre> <p>you're are saying a completely different thing; <code>string</code> here is not a C-string (i.e. a <code>char[]</code>), but the C++ <code>std::string</code> type, which is a class that manages a dynamic string; those two things are completely different.</p> <p>If you want to obtain a constant C-string (<code>const char *</code>) from a <code>std::string</code> you have to use it's <code>c_str()</code> method. Still, you can't use the pointer obtained in this way with <code>strtok</code>, since <code>c_str()</code> returns a pointer to a <strong><code>const</code></strong> C-string, i.e. it cannot be modified. Notice that <code>strtok</code> is not intended to work with C++ strings, since it's part of the legacy C library.</p> <blockquote> <p>also if we write const string n = "n"; and pass it as second argument it doesnt work...this was my first problem...</p> </blockquote> <p>This doesn't work for the exact same motivation, but in this case you can simply use the <code>c_str()</code> method, since the second argument of <code>strtok</code> is a <strong><em><code>const</code></em></strong> <code>char *</code>.</p> <blockquote> <p>now also the sizeof(name) output is 8 but it should be 4 as avinash has been tokenised.. </p> </blockquote> <p><code>sizeof</code> returns the "static" size of its operand (i.e. how much memory is allocated for it), it knows nothing about the content of <code>name</code>. To get the length of a C-string you have to use the <code>strlen</code> function; for C++ <code>std::string</code> just use its <code>size()</code> method.</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