PDA

Archiv verlassen und diese Seite im Standarddesign anzeigen : Verständnissfrage zu Strukturen in c++


Lord Nikon
2004-04-27, 17:32:30
Hi,
hier ist der Code ausschnitt

struct pixel_8
{
uchar red, green, blue;

pixel_8( void ) : red( 0 ), green( 0 ), blue( 0 ) { }
pixel_8( uchar r, uchar g, uchar b ) : red( r ), green( g ), blue( b ) { }
};



void directx_surface::set_palette( pixel_8 *colors )
{
PALETTEENTRY palette_definition[ 256 ];
memset( palette_definition, 0, 256*sizeof( PALETTEENTRY ) );

for( ushort x=0 ; x<256 ; x++ )
{
palette_definition[ x ].peRed = colors[ x ].red;
palette_definition[ x ].peGreen = colors[ x ].green;
palette_definition[ x ].peBlue = colors[ x ].blue;
palette_definition[ x ].peFlags = PC_NOCOLLAPSE;
}

Ich verstehe nicht richtig, warum man die Strukur hochzählen kann,obwohl diese kein Array ist.In c# geht dies jedenfalls nicht.

ethrandil
2004-04-27, 18:13:58
Also, wenn ich dich richtig verstehe möchtest du wissen, warum man in c++ auf "pixel_8 *colors" per "colors[x]" zugreifen kann, richtig?

In diesem Fall verfährt der Compiler so, dass er *colors als einen Pointer auf das erste Element eines pixel_8-Arrays interpretiert.
d.H. wenn ein pixel_8-Objekt (oder struct) 3 Byte lang ist, dann verweise colors[1] auf die Speicherstelle 3 Bytes dahinter.

Ich find das unschön, das ist aber vielleicht performanter.

- Eth

EDIT:
Gibt es in c# überhaupt Pointer? Ansonsten wäre dazu zu sagen, dass c# ein bisschen typensicherer ist.

Lord Nikon
2004-04-27, 18:38:19
Thx, jetzt habe ich das verstanden.
In c# kann man noch Pointer nutzen, wenn man das Schlüsselwort unsafe benutzt.
EDIT:
Unfair:
For this reason a pointer is not permitted to point to a reference or to a struct that contains references, and the referent type of a pointer must be an unmanaged-type.

An unmanaged-type is any type that isn't a reference-type and doesn't contain reference-type fields at any level of nesting. In other words, an unmanaged-type is one of the following:

sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.

HellHorse
2004-04-27, 18:46:17
Und das Array sollte mindestens 256 Elemente lang sein, sonst kommt Freude auf ...

Lord Nikon
2004-04-27, 19:30:40
Der Aufruf von set_palette:

void change_palette( void )
{
pixel_8 palette[ 256 ];

ushort x, c;
for( x=0, c=0 ; x<64 ; x++, c+=4 )
{
palette[ x ] = pixel_8( c, 0, 0 );
palette[ x+64 ] = pixel_8( c, c, c );
palette[ x+128 ] = pixel_8( 0, c, 0 );
palette[ x+192 ] = pixel_8( 0, 0, c );
}

surface.set_palette( palette );
}

Daraus folgt das die 256 immer abgesichert ist.