Confusion about static arrays

torhu fake at address.dude
Sat Jan 27 23:47:08 PST 2007


Rick Mann wrote:
> I had a little hiccup earlier when I tried to do this:
> 
> 	static EventTypeSpec[1] events =
> 	[
> 		{ EventClass.kEventClassWindow, kEventWindowBoundsChanged }
> 	];
> 	writefln("events: 0x%x", events);
> 
> (EventTypeSpec is a struct with two uint members).
> 
> This resulted in a bus error inside writefln(). Someone pointed out that I should pass events.ptr, which works. However, from the examples in (http://www.digitalmars.com/d/arrays.html). For example, it says that static arrays are analogous to C arrays. It also suggests this:
> 
> int* p;
> int[3] s;
> int[] a;
> 
> p = s;		// p points to the first element of the array s.
> p = a;		// p points to the first element of the array a.
> 
> In both cases, assigning from s or a results in something pointing to the first element of s and a. 
> 
> I guess I have two questions:
> 
> a) why would passing "events" to writefln() (with that specific format specifier) cause it all to crash
> 
I don't know, you would have to look at the source code that comes with 
dmd to see why it crashes.  "%x" is definitely not the correct format 
specifier for an array, though.  The real problem is that writefln 
doesn't seem to know what to do with structs.  Crashing is not a great 
solution, though.

You can either do this:
writefln("events: 0x%x, 0x%x", events[0].field1, events[0].field2);

Or you can give the struct a toString() member.  Then you can use "%s" 
as the format, or just nothing at all.  writefln (which I seem to 
remember uses std.format.doFormat) will call your toString for each element.

char[] toString()
{
     return "{" ~ std.string.toString(field1) ~ ", " ~
                     std.string.toString(field2)  "}";
}

  b) Is the spec web page incorrect (or is it reasonable to be mislead 
by its wording) when it seems to imply that one can simply pass the name 
of the array around, rather than .ptr?
> 
The name of the array doesn't get implicitly converted to a pointer to 
the data anymore. Other than that, you can pass arrays around as you 
please.  Be aware that static arrays are also passed as length + pointer 
when used as variadic arguments, which messes up things when used with a 
C api.


More information about the Digitalmars-d-learn mailing list