Bus error accessing char [] by index - OS X
Regan Heath
regan at netmail.co.nz
Wed Nov 7 02:31:04 PST 2007
Regan Heath wrote:
> Regan Heath wrote:
>> Cam MacRae wrote:
>>> BCS Wrote:
>>>
>>>> Reply to Cam,
>>>>
>>>>
>>>> On linux, string literals are in read only memory space. As for OS
>>>> X...???
>>>>
>>>>
>>>
>>> Thanks mate - that could be it. I was just following along the D
>>> Transition guide (http://en.wikibooks.org/wiki/D_Transition_Guide).
>>> Perhaps it's out of date...
>>
>> More like "windows centric" as string literals can be written to on
>> windows.
>>
>> Simple fix:
>>
>> char[] a = firstname.dup, b = firstname;
>> a[0] = 'H'; //5
>
> Actually, this breaks the example entirely as b is no longer modified by
> a[0] - 'H' oops.
Here is my suggested fix - I don't have DMD 1.0 to test this with so
someone else is going to have to edit the wiki (after testing this works!)
import std.stdio;
void main() {
char[] firstname, lastname, fullname; //1
firstname = "Walter".dup; //2
lastname = "Bright"; //3
fullname = firstname ~ " " ~ lastname; //4
writefln("Congratulations on making a great language " ~
fullname); //5
char[] a = firstname, b = firstname;
a[0] = 'H'; //6
writefln(b); //prints "Halter"
writefln("Your name is still %s, right?", fullname); //7,
prints Walter Bright
}
1. Strings are nothing more than character arrays. You'll see more
about arrays later, but for now, know that character arrays are not a
special case. The one major note is that D strings are not null
terminated. Arrays simply keep track of their length.
2. dup used here to create a copy of the string "Walter" (this is
because string literals are read-only on some OS's)
3. No strcpy here. In fact, this is more like reassigning a pointer
(ie, char *lastname = "Bright").
4. ~ is the concatenation operator. There is no ambiguity between +
and ~ for strings.
5. One way of outputting, although number 7 is better
6. Since a is really a pointer to firstname, firstname (and hence b)
actually get modified on this line.
7. But since fullname was created through concatenation, it remains
unchanged.
More information about the Digitalmars-d
mailing list