# Pointer and array

## 1.How is memory laid out for a program?

* Memory is divided into **blocks** of a certain size (32-bits or 64-bits depending on the OS)
* Each block has a specified address
  * This means every location in memory can be accessed by using its address
* 變數是參照某位置, 值是儲存該位置的值
* pointer是指向某位置, 值是儲存該位置

```
int radius = 25;
int *rasdiudPtr = &radius;
int *otherRsdiudPtr;
otherRsdiudPtr = rasdiudPtr;
int r = *rasdiudPtr;

printf("%u\n", &radius); //123FF
printf("d\n", *&radius); //25
printf("%d\n", *rasdiudPtr); //25
printf("%u\n", rasdiudPtr); //11DA
printf("%u\n", &radiusPtr); //123FF
printf("%u\n", &otherRsdiudPtr); //AB24
```

## 2.Why pointer need a type?

* How mush space does stuff occupy
  * Integer: 4 bytes
  * Float: 4 bytes
  * Char: 1 bytes

## 3.Arrays in C are actually pointers

* **Array variables are simply pointers**
  * int \*: arr is a pointer to an integer and it points to the address location of the very first element in the integer array

```
int arr[4] = {1, 2, 3, 4};
int *intptr = arr;
intptr++;
```

## 4.Problem 1

```
int length = 10;
int breadth = 5;
int *length_ptr = &length;
int *breadth_ptr = &breadth;

printf("%d\n", *length_ptr); // 10
printf("%d\n", *breadth_ptr); //5
```

## 5.Problem 2

```
int length = 10;
int breadth = 5;
int *length_ptr = &length;
int *breadth_ptr = &breadth;

printf("%u\n", length_ptr); // OX7F
printf("%u\n", breadth_ptr); //OX77
```

## 6.Problem 3

```
int length = 10;
int breadth = 5;
int *length_ptr = &length;
int *breadth_ptr = &breadth;
int *test = length_ptr;
*test = 25;

printf("%d\n", length); //25
printf("%d\n", breadth); //5
```



## 7.Problem 4

```
int length = 10;
int breadth = 5;
int *length_ptr = &length;
int *breadth_ptr = &breadth;
int *test = length_ptr;
*test = 25;

printf("%d\n", length); //25
printf("%d\n", breadth); //5

test = breadth_ptr;
*test = 20;

printf("%d\n", length); //25
printf("%d\n", breadth); //20
```
