array
-
Abend
Kann eine Funktion float[4] zurückgeben?
hab eine klasse mit float r, g, b, a
und möchte eine funktion, die eine Refernez auf ein float color[4] = {r, g, b, a} zurückgibt, wie kann man das machen?
thx
-
void some_function(float* pBuf) { pBuf[0] = r; pBuf[1] = g; pBuf[2] = b; pBuf[3] = a; } // ... float f[4]; some_function(f);
-
float (&fun1())[4]; typedef float f_array[4]; f_array& fun2();
-
Oder:
struct color{ float r; float g; float b; float a; }; //... color myFunc(){ color c; // ... return c; } //... color c; float *f = (float*)&(c = myFunc()); float r = f[0]; float g = f[1]; float a = f[3];
Aber keine Ahnung warum man sowas machen sollte.
-
Schöner wäre es gleich ohne Casten die Struktur zu verwenden da sie zum einen eine gewisse Sicherheit hat, zum anderen auch lesbarer ist...
Sprich Fellhuhn's Beispiel ohne anschließende Casts (color c = myFunc();)
cu André
-
Wenn man davon ausgeht, das er nicht eine Bibliothek benutzt die ein float-Array erwartet.
-
Fellhuhn schrieb:
Wenn man davon ausgeht, das er nicht eine Bibliothek benutzt die ein float-Array erwartet.
Dann aber lieber so:
struct color { float c[4]; }; //... color myFunc(){ color c = { { r, g, b, a } }; // ... return c; } //... color c = myFunc(); float* f = &c.c[0]; float r = f[0]; float g = f[1]; float a = f[3];
-
Das wird aber unübersichtlich wenn r,g,b und a durch komplexe trigonometrische Quantensprungshyperfunktionen mit Parabeleinlauf berechnet werden.
Dann doch gleich:
float *myFunc(){ static color c = { { r, g, b, a } }; // ... return (float*)&c; } //... float* f = myFunc(); float r = f[0]; float g = f[1]; float a = f[3];
Das sorgt für Chaos.
-
Du kannst nicht davon ausgehen, dass das funktioniert. Auf einem 64-bit System könnte der Kompiler hier schon Padding anwenden, da float nur 32-biit groß ist. Dann wunderst du dich über komische Ergebnisse.
-
Und dann regnet es Schafe, dann geht das auch nicht. Außer es ist Donnerstag. :p