1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| int n = 10; int *pn = &n; int **ppn = &pn;
n = 3; *pn = 3; **ppn = 3;
printf("%p", &n); printf("%p", pn); printf("%p", *ppn);
printf("%p", &pn); printf("%p", ppn);
printf("%p", &ppn);
|
Assign a value to a variable
- Step 1:
int a
Allocate a piece of memory for a, so a points to this ‘memory block’.
- Step 2:
a = 5
Store 5 (in binary) in this memory block.
store the input value into the piece of memory that a points to.
About int*
The variable, is p
, not *p. p
points to a new piece of memory that stores the address of a.
About int**
The variable is q
, not q or *q. q
stores the memory location of p.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include <stdio.h> int main() { char *s1 = "CS354"; char *s2 = "is"; char *s3 = "awesome";
printf("s1: %p \n", s1); printf("*s1: %c \n", *s1); printf("*(s1+1): %c \n", *(s1+1)); printf("\n"); char *pca[3] = {s1, s2, s3}; printf("pca[0]: %p \n", pca[0]); printf("*pca[0]: %c \n", *pca[0]); char **ppca = pca; printf("\n"); printf("ppca[0]: %s \n", ppca[0]); printf("ppca[1]: %s \n", ppca[1]); printf("ppca[2]: %s \n", ppca[2]); return 0; }
|
The output:
1 2 3 4 5 6 7 8 9 10
| s1: 0x102cb5f34 *s1: C *(s1+1): S
pca[0]: 0x102cb5f34 *pca[0]: C
ppca[0]: CS354 ppca[1]: is ppca[2]: awesome
|