# HackMD
學習日期:5/2
## Pointer
- Addr, Type, and Value
- First test program
```c=
int main(){
int x = 100;
printf("x = %d at addr = %p\n", x, &x);
return 0;
}
```
- The result:

## 全域變數&區域變數
1.全域變數的儲存位置與區域變數不同
2.全域變數可用的記憶體比區域變數大
- The test program
```c=
int z = 10000;
int main(){
int x = 100, t[10]={1,2}, y=1000;
printf("x = %08x at addr = %p\n", x, &x);
printf("t[0] = %08x at addr = %p\n", t[0], &t[0]);
printf("t[1] = %08x at addr = %p\n", t[1], &t[1]);
printf("t[2] = %08x at addr = %p\n", t[2], &t[2]);
printf("y = %08x at addr = %p\n", y, &y);
printf("z = %08x at addr = %p\n", z, &z);
return 0;
}
```
- The result

## 從記憶體位置提取數值
- 在變數位置前加上* 可提取原本的數值
- The test program
```c=
int main(){
int x = 100;
printf("x = %08x at addr = %p\n", x, &x);
printf("Value = %d at addr = %p\n", *(&x), &x);
return 0;
}
```
- The result

- Note
1.& can be put in front of a variable => get the address of that address
2.* can be put in front of an address => get the value of that address
3.%p is used as the address specifier for printf
## 整數的指標
- 有點像門牌的概念
- The test program 1
```c=
int main(){
int x = 100;
int *xp = &x;
printf("x = %d at addr = %p\n", x, xp);
printf("Value = %d at addr = %p\n", *xp, xp);
printf("xp also has address = %p\n", &xp);
return 0;
}
```
- The result 1

- The test program 2
```c=
int main(){
int x = 100;
int *xp = &x;
*xp = 200;
printf("x = %d at addr = %p\n", x, &x);
printf("x = %d at addr = %p\n", *xp, xp);
return 0;
}
```
- The result 2

- The test program 3
```c=
int main(){
int x = 100;
int *xp = &x;
int *zp = xp;
*zp = 200;
printf("x = %d at addr = %p\n", x, &x);
printf("x = %d at addr = %p\n", *zp, zp);
return 0;
}
```
- The result 3

## 作業
- Practice 1
```c=
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void getAB(int guess, int answer, int *x, int *y)
{
int i, j;
int guess_digits[4], answer_digits[4];
for (i = 3; i >= 0; i--) {
guess_digits[i] = guess % 10;
guess /= 10;
answer_digits[i] = answer % 10;
answer /= 10;
}
*x = *y = 0;
for (i = 0; i < 4; i++) {
if (guess_digits[i] == answer_digits[i]) {
(*x)++;
} else {
for (j = 0; j < 4; j++) {
if (guess_digits[i] == answer_digits[j]) {
(*y)++;
break;
}
}
}
}
}
int main()
{
int answer[4];
int guess;
int a, b;
int i, j;
srand(time(NULL));
for (i = 0; i < 4; i++) {
answer[i] = rand() % 10;
for (j = 0; j < i; j++) {
if (answer[i] == answer[j]) {
i--;
break;
}
}
}
int answer_int = 0;
for (i = 0; i < 4; i++) {
answer_int = answer_int * 10 + answer[i];
}
printf("請開始猜測!\n");
while (1) {
printf("請猜測一個四位數字(不重複):");
scanf("%d", &guess);
if (guess == answer_int) {
printf("恭喜你猜中了,答案是%d!\n", guess);
break;
}
getAB(guess, answer_int, &a, &b);
printf("%dA%dB\n", a, b);
}
return 0;
}
```
- 結果

- Practice 2


- Practice 3


- Practice 4

