... notes by A.Kamburelis ... will be expanded and translated Δομές της C (struct = structures) Δήλωση του νέου τύπου : struct όνομα { τα πεδία (μέλη) της δομής }; π.χ. complex numbers in C #include struct complex { float Re; float Im; }; main(){ struct complex z1, z2; // Δήλωση μεταβλητών printf("sizeof = %d\n", sizeof(struct complex)); printf("give z1.Re -> "); scanf( "%f", &z1.Re ); // reading z1.Im := 55; z2 = z1; // NEW STUFF! printf("z2 = %f + i * %f \n", z2.Re, z2.Im ); } Note: assigning struct to struct, like z2=z1 above, assumes that they have same type! Structs inside structs eg. color and pixel #include struct color { int r,g,b; }; struct pixel { int x,y; struct color c; // <- struct inside struct }; main(){ struct pixel p; struct color blue; blue.r = blue.g = 0; blue.b = 255; // create blue p.x = 12; p.y = 50; p.c = blue; // set pixel color to blue p.c.r = 50; // correct red of p, but NOT of blue } Συναρτήσεις και Δομές Example: struct color MyColor ( int Red, int Green, int Blue){ struct color temp; // prepare temp and return it temp.r = Red; temp.g = Green; temp.b = Blue; return temp; } using: blue = MyColor(0,0,255); Returning to our example with complex numbers. #include struct complex { float Re,Im; }; // example: a function that takes structs, and returns a struct struct complex add ( struct complex a, struct complex b ){ struct complex help; help.Re = a.Re + b.Re; help.Im = a.Im + b.Im; return help; } main(){ struct complex z1, z2, z3; z1.Re=z1.Im = 1; // z1=1+i z2.Re=z2.Im = 6; // z2=6+6i, so z1+z2=7+7i z3=add(z1,z2); // call add printf("z3 = %f + i * %f \n", z3.Re, z3.Im ); } The next remark applies only to C++, but Visual Studio and DevCpp uses C++ already! In C++ we have operator overloading! For example, the + operator can be overloaded, to work with our complex numbers. To do so, write: struct complex operator+ ( struct complex a, struct complex b ) struct complex help; help.Re = a.Re + b.Re; help.Im = a.Im + b.Im; return help; } Now, in main, use just : z3 = z1 + z2; // it works! You can overload also operators like : -, *, / and %. Unions (not in lab material). // Endian example union trick { int n; unsigned char p[4]; }; void TestEndian (){ union trick t; // we want to show the 32 bit number $00 01 02 03 // this value is 1*(256)^2 + 2*256 + 3 t.n = 1*256*256 + 2*256 + 3; // print bytes of t.n exactly as they are located in RAM printf("%d %d %d %d\n",t.p[0],t.p[1],t.p[2],t.p[3]); } Search for "endianness" in WikiPedia.