Can't assign string to char * like the docs say

Steven Schveighoffer schveiguy at yahoo.com
Wed May 13 13:42:51 PDT 2009


On Wed, 13 May 2009 14:28:46 -0400, Doctor J <nobody at nowhere.com> wrote:

> Taken straight from http://www.digitalmars.com/d/1.0/arrays.html, this  
> doesn't compile:
>
>     void main()
>     {
>         string str = "abc";
>         char* p = str;		// pointer to 1st element
>     }
>
> "Error: cannot implicitly convert expression (str) of type char[] to  
> char*"
>
> I agree it shouldn't compile; I guess I'm asking why the docs say it  
> does.
>
> While I'm at it, what's up with the very first strings example:
>
>     char[] str;
>     char[] str1 = "abc";
>     str[0] = 'b';        // error, "abc" is read only, may crash
>
> Should that just be:
>
>     char[] str = "abc";
>     str[0] = 'b';        // error, "abc" is read only, may crash
>
>


To make this more clear, the example text from the array page says:

A pointer to a char can be generated:
char* p = &str[3];	// pointer to 4th element
char* p = str;		// pointer to 1st element

where str is previously identified as a string (i.e. char[])

it is a documentation bug, this behavior is not allowed.  Please submit a  
bug to bugzilla: http://d.puremagic.com/issues/

On the other hand, string *literals* are implicitly castable to char *:

char *p = "abc";

works.

-Steve


More information about the Digitalmars-d-learn mailing list