# [AIdrifter CS 浮生筆錄](https://hackmd.io/s/rypeUnYSb) <br> Pointer,Address, and String
## Array and Address
```C
// assume a's address = 100
// assume b's address = 200
// assume c's address = 300
// assume d's address = 400
int a[4], *b, *c;
char s[10];
for (i=0; i<4; i++)
a[i] = i;
b = a;
c = &a[2];
strcpy(s,“123”);
```
- Question
```C
printf(“%c”, s); // ?? (S 的 Addr 轉成 char)
printf(“%d”, s[0]); // 49 (‘1’ 的 ASCII code)
printf(“%s”, s[0]); // Runtime error(crash)
printf(“%c”, s[0]); // 1
```
## String Array
```
char a[100];
strncpy(a, "123");
char s1[] = "abcde";
char *s2 = "abcde";
char *s3;
s3 = malloc(6);
strcpy(s3, "abcde");
```
![](https://i.imgur.com/Ky12fEB.png =x300)
- Question
```C
s1 = a; // compile error
s2 = a; // OK
s3 = a; // OK, but memory leak
strcpy(s1, a); // OK, stack can rw
strcpy(s2, a); // [FIXME] Wrong => code seegment (read only)
strcpy(s3, a); // OK, heap can rw
```
- String Coding Style
```C
#define LEN 5
char s1[LEN],s2[LEN];
strncpy(s1,”abcdefgh”,LEN-1);
s1[LEN-1] = ‘\0’;
// | | | | | |
// s1[5] |a |b |c |d |\0 |
// 0 1 2 3 4
strncpy(s2,”ab”,LEN-1);
s2[LEN-1] = ‘\0’;
// | | | | | |
// s2[5] |a |b |\0 |? |\0 |
// 0 1 2 3 4
```
## Pointer To Pointer
- ~~Double Pointer~~ 是錯誤的說法 Jserv大神會生氣喔
### 2D Array
- dynmically allocate array size
```C
int i;
int N = 3,M = 5;
int **a = NULL;
a = (int **)malloc(sizeof(int *)*N);
if (a)
{
for (i=0; i<N; i++)
{
a[i] = (int *)malloc(sizeof(int)*M);
if (!a[i])
break;
}
} // (i != N) or (a == NULL) => malloc() failed
```
![malloc() 2d array](https://i.imgur.com/fd2zMq2.png =x350)
- How to free it ?
```C
if (a)
{
for (i=0; i<N; i++)
free(a[i]);
free(a);
a = NULL;
}
```
![](https://i.imgur.com/YTglSzf.png =x250)
### Pointer as Parameter
- `*b` <=> `a`
```C
int foo (int **b)
{
int i=0, n=10;
if ((*b = (int *)malloc(n * sizeof(int))) == NULL)
return 0;
for (i=0;i<n;i++)
(*b)[i] = i; // important!!! (*b) <=> a
return n;
}
int main()
{
int *a = NULL;
int n = 0, i;
if ( n=foo(&a) )
{
for (i=0;i<n;i++)
printf("%d\n", a[i]);
if(a)
{
free(a);
a = NULL;
}
}
}
```
- **`*b`(pointer to pointer) <=> `a`(pointer)**
![](https://i.imgur.com/uDYjmIb.png =x300)
![](https://i.imgur.com/Lzd3zdN.png =x330)