Array and pointer
©T©w¤j¤pªºarray«Å§i:
¨Ò¦p:
float A[11];
const int n = 22;
int B[n];
Â÷¶}scope´N¦Û°Ê®ø¥¢.
Pointer(«ü°w)ªº«Å§i
¨Ò¦p:
n
float* A; // A¬O¤@Ó
float pointer
n
float *A; // ©Î¸ÑÄÀ¦¨: A©Ò«üªºÈ¬O¤@Ó float
n
float * A; // ³o¼Ë¤]¥i¥H
¦ý
n
float *A, B; // B¬O float,¤£¬O float pointer
n
float* A, B; // ÁÙ¬Oªº, B¬O float,¤£¬O float pointer
*: referencing operator
&: address-of operator
Y ptr ¬O¤@Ó pointer, *ptr ´N¬O ptr©Ò¦b¦ì¸mªº¤º®e.
¨Ò¦p:
float a = 6.13;
float *p = &a; // p is the
address of a
cout << ¡§Address: ¡§ <<
p << ¡§Content:¡¨ << *p << endl;
§A´N·|¬Ý¨ì¤Q¤»¶i¦ìªº¦ì§}¤Î¤º®e.
Dynamic
Memory Allocation(°ÊºA°O¾Ð¤À°t)
¨Ò¦p:
int n;
// n ªºÈ(>0)¦b¬Y³B±o¨ì
n float *A = new float [n];
©Î
n
float
*A;
A = new float [n];
¸ÑÄÀ¦¨: A ¬O¤@Ó«üµÛnÓfloatªºpointer.
new ¥X¨ÓªºªF¦è,¤£¥Î®É¤@©wn delete±¼!
delete [] A;
©Î
double* b = new double;
// ..... b ¤£¥Î¤F
delete b;
§_«h,©Ò¦û¥ÎªºªÅ¶¡±N¤@ª½³Q¦û¥ÎµÛ,ª½¨ìµ{¦¡²×µ²!
½m²ß: n¬°©_¼Æ.
¥Í¦¨ n
x
n Magic Square
(¤¸¯À¬° 1,2,3,...,n^2 ªº¤è°},¨ä ¥ô¤@¦æ¡N¥ô¤@¦CªºÁ`¦X ¬Òµ¥©ó¦U±×¹ï¨¤ªºÁ`¦X)
³o¸Ì¦³¤@Ó²{¦¨ªº³W«h:
±q²Ä¤@¦Cªº¤¤¶¡¶}©l(³]¬°1),¤U¤@ÓÈ(§Y2)©ñ¦bºò¾Fªº¥k¤W¤è - ¤£¹L,¦]¬°¶W¥X¦C¬É,¬G©ñ¦b³Ì«á¤@¦C.
¨Ì¦¹³W«h (±N¤U¤@ÓÈ©ñ¦bºò¾Fªº¥k¤W¤è) Ä~Äò:
n Y¦¹¦ì¸m¥¼¶W¥X¦æ¦C¬É:
Y¦¹¦ì¸m©|¥¼¶ñ¤J,«h±N¤U¤@ÓÈ©ñ¸m©ó¦¹,§_«h¸m©ó¥¿¤U¤è
n Y¦¹¦ì¸m¶È¶W¥X¦C¬É,«h¸m©ó¦P¦æ³Ì«á¤@¦C
n Y¦¹¦ì¸m¶È¶W¥X¦æ¬É,«h¸m©ó¦P¦C³Ì«e¤@¦æ
n Y¦¹¦ì¸m¦P®É¶W¥X¦æ»P¦C¬É,«h©ñ¦b¥¿¤U¤è.