# 指標與位址

``````#include <stdio.h>

int main(void) {
int n = 10;

printf("n 的值：%d\n", n);
printf("n 的位址：%p\n", &n);

return 0;
}
``````

``````n 的值：10
n 的位址：0061FECC
``````

``````type *ptr;
``````

`ptr` 可儲存位址，而 `type` 為該位址儲存值的型態，實際宣告的方式如下：

``````int *n;
float *s;
char *c;
``````

``````#include <stdio.h>

int main(void) {
int n = 10;
int *p = &n ;

printf("n 的位址：%p\n", &n);
printf("p 儲存的位址：%p\n", p);

return 0;
}
``````

``````n 的位址：0061FEC8
p 儲存的位址：0061FEC8
``````

``````#include <stdio.h>

int main(void) {
int n = 10;
int *p = &n;

printf("指標 p 儲存的值：%p\n", p);
printf("取出 p 儲存位址處之值：%d\n", *p);

return 0;
}
``````

``````指標 p 儲存的值：0061FEC8

``````

``````#include <stdio.h>

int main(void) {
int n = 10;
int *p = &n ;

printf("n = %d\n", n);
printf("*p = %d\n", *p);

*p = 20;

printf("n = %d\n", n);
printf("*p = %d\n", *p);

return 0;
}
``````

``````n = 10
*p = 10
n = 20
*p = 20
``````

``````int *p;
*p = 10;
``````

``````int *p = 0;
``````

``````int *p1;
int* p2;
int * p3;
``````

``````int* p1, p2;
``````

``````int *p1, *p2;
``````

``````void *p;
``````

`void*` 型態的指標沒有任何型態資訊，只用來儲存位址，不可以使用 `*` 運算子對 `void*` 型態指標提取值，而必須轉型至對應的型態，例如：

``````#include <stdio.h>

int main(void) {
int n = 10;
void *p = &n ;

// 下面這句不可行，void 型態指標不可取值
// printf("%d\n", *p);

// 轉型為int型態指標並指定給iptr
int *iptr = (int*) p;
printf("%d\n", *iptr);

return 0;
}
``````

``````10
``````

``````const int n = 10;
int *p = &n; //  warning: initialization discards 'const' qualifier from pointer target type
*p = 20;
printf("%d\n", n);
``````

``````const int n = 10;
const int *p = &n;
*p = 20; // error, assignment of read-only location
``````

``````int x = 10;
int y = 20;
int* const p = &x;
p = &y;  // error,  assignment of read-only variable `p'
``````

``````const int x = 10;
const int y = 20;
const int* const p = &x;
p = &y;  // error,  assignment of read-only variable `p'
``````