Frage zu Array int[x,x];
-
Ich hab hier irgendwo eben im Forum diesen Code entdeckt.^^
int* foobar = new int[2,4]; foobar[0,2] = 5; foobar[1,2] = 10; cout << foobar[1,2]; delete [] foobar;Ich kenne wohl sowas wie z.b.: int *[2][4];
Aber sowas wie oben habe ich noch nicht gesehen was bedeutet denn die 2,4?
Werden da 2,4 Elemente erstellt? ... Wohl er nicht. Kann mir jemand erklären was das ist?
-
2,4ist4. Nicht jeder Code hier im Forum ist richtig. Guck immer, von wem er stammt oder was der Autor damit ausdrücken wollte. Lies diesen Beitrag (aus dem du das wohl hast) mal vollständig und aufmerksam:
http://www.c-plusplus.net/forum/p2245931#2245931
Der Autor (Michael E.) wollte nämlich an einem vereinfachten Beispiel erklären, was für ein Unsinn diese Art von Code ist.edit: Falls dir der Hintergrund zu der hier benutzten Syntax fehlt:
http://en.wikipedia.org/wiki/Comma_operator
-
n3337 schrieb:
5.18 Comma operator [expr.comma]
1 The comma operator groups left-to-right.
expression:
assignment-expression
expression , assignment-expressionA pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded-value expression (Clause 5).83 Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression. The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand, and is a bit-field if its right operand
is a glvalue and a bit-field.2 In contexts where comma is given a special meaning, [ Example: in lists of arguments to functions (5.2.2) and lists of initializers (8.5) — end example ] the comma operator as described in Clause 5 can appear only in parentheses. [ Example:
f(a, (t=3, t+2), c);
has three arguments, the second of which has the value 5. — end example ]
Der Ausdruck
2,4hat den Wert 4, der Teilausdruck 2 hat den Wert 2, dieser Wert wird aber verworfen; da der Ausdruck 2 keine Seiteneffekte hat, bewirkt er absolut nichts.
int* foobar = new int[2,4];und
int* foobar = new int[4];haben exakt den gleichen Effekt.
-
Der Code Auszug vom Initialen Post stammt von hier (1. Post von Michael E.):
http://www.c-plusplus.net/forum/307452Nur wegen der Vollständigkeit...
-
Das geht doch super:
int main() { twodarr<int> a(2, 5); a[O, 2] = 3; a[O, 4] = 10; for (int i = 0; i < 5; ++i) std::cout << a[O, i] << ' '; std::cout << "\b\n"; }Man muss sich halt das Array selber schreiben.
enum index_e { O=0, I, II, III }; struct index_proxy { int y, x; index_proxy(int y, int x) : y(y), x(x) {} }; index_proxy operator,(index_e y, int x) { return index_proxy(static_cast<int>(y), x); } template <typename T> class twodarr { std::vector<T> data; int w; public: typedef T type; twodarr(int h, int w) : data(w*h), w(w) {} type& operator[](index_proxy pos) { return data[w*pos.y + pos.x]; } };