Note that there are some explanatory texts on larger screens.

plurals
  1. POconst pointer assign to a pointer
    text
    copied!<p>Why can I not do this:</p> <pre><code>char* p = new char[10]; void SetString(char * const str) { p = str; } SetString("Hello"); </code></pre> <p>I have a const pointer to a char, why can I not assign the const pointer to another pointer?</p> <p>It just seems illogical, as by assigning it to another pointer, you are not essentially violating the const-ness of the char pointer. Or are you?</p> <p>EDIT: When I compile this it says "error C2440: '=' : cannot convert from 'char *const *__w64 ' to 'char *'"</p> <p>(I'm attempting to understand a concept from a book I'm reading. Just cannot get the code to compile.</p> <p>CODE:</p> <pre><code>int _tmain(int argc, _TCHAR* argv[]) { MyString *strg = new MyString(10); strg-&gt;SetString("Hello, "); MyString *secondstr = new MyString(7); secondstr-&gt;SetString("Tony"); strg-&gt;concat(*secondstr, *strg); } </code></pre> <p>CPP FILE:</p> <pre><code>#include "MyStringClass.h" #include &lt;string.h&gt; #include "stdafx.h" #include "MyStringClass.h" void MyString::concat(MyString&amp; a, MyString&amp; b) { len = a.len + b.len; s = new char[len + 1]; strcpy(s, a.s); strcat(s, b.s); delete [] s; } void MyString::SetString(char * const str) { s = str; } MyString::MyString(int n) { s = new char[n+1]; s[n+1] = '\0'; len = n; } </code></pre> <p>HEADER FILE:</p> <pre><code>#include &lt;string.h&gt; #include &lt;stdio.h&gt; class MyString { private: char* s; int len; public: MyString(int n = 80); void SetString (char * const str); void concat (MyString&amp; a, MyString&amp; b); }; </code></pre>
 

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