---
# System prepended metadata

title: Pointer

---

# Pointer

- Addr, Type, and Value
- First test program

筆記 1
```c=
#include <stdio.h>

int main(){
    int x = 100;
    printf("x = %d at addr = %p\n", x, &x);
    return 0;
}
```
結果
![](https://i.imgur.com/BSfL4B9.png)

## Practice 1
```c=
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int answer[4];
    int guess[4];
    int i, j, x, y, num_guesses;
    char input[5];
    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;
            }
        }
    }
    num_guesses = 0;
    do {
        printf("Enter your guess (4 digits): ");
        scanf("%s", input);
        for (i = 0; i < 4; i++) {
            guess[i] = input[i] - '0';
        }
        x = y = 0;
        for (i = 0; i < 4; i++) {
            if (guess[i] == answer[i]) {
                x++;
            } else {
                for (j = 0; j < 4; j++) {
                    if (guess[i] == answer[j]) {
                        y++;
                        break;
                    }
                }
            }
        }
        printf("%dA%dB\n", x, y);
        num_guesses++;

    } while (x < 4);
    printf("Congratulations! You guessed the answer in %d guesses.\n", num_guesses);
    return 0;
}

```
結果
![](https://i.imgur.com/ByLZQKJ.png)

## practice 2
```c=
#include <stdio.h>

int main() {
    int a[10];

    printf("a: %p\n", a);
    printf("&a: %p\n", &a);
    printf("&a[0]: %p\n", &a[0]);
    printf("&a[3]: %p\n", &a[3]);
    printf("a+3: %p\n", a+3);

    for (int i=0; i<10; i++) {
        scanf("%d", a+i);
    }

    return 0;
}
```

## practice 3
```c=
#include <stdio.h>

int main() {
    int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int *ap = a;

    printf("ap[0]: %d\n", ap[0]);

    for (int i=0; i<10; i++) {
        printf("a[%d]: %d\n", i, a[i]);
        printf("ap[%d]: %d\n", i, ap[i]);
        printf("*(a+%d): %d\n", i, *(a+i));
        printf("*(ap+%d): %d\n", i, *(ap+i));
    }

    a++;
    a+=3;
    printf("a+3: %p\n", a);

    ap++;
    ap+=3;
    printf("ap+3: %p\n", ap);

    printf("ap-a: %ld\n", ap-a);

    return 0;
}
```

## practice 4
```c=
#include <stdio.h>

int main() {
    int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int *ap = a;

    printf("Size of a: %ld bytes\n", sizeof(a));
    printf("Size of a[0]: %ld bytes\n", sizeof(a[0]));
    printf("Number of elements in a: %ld\n", sizeof(a) / sizeof(a[0]));

    return 0;
}
```