[CS354-1]Pointers in C

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;

// To access n
n = 3;
*pn = 3; // dereference
**ppn = 3; // dereferencing twice

// To access the address of n
printf("%p", &n);
printf("%p", pn); // pn is the exactly the address of n
printf("%p", *ppn);

// To access the address of pn
printf("%p", &pn);
printf("%p", ppn);

// To access the address of ppn
printf("%p", &ppn);

Assign a value to a variable

1
int a = 5;
  • 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.
1
scanf("%d", &a);

store the input value into the piece of memory that a points to.

About int*

1
int* p = &a;

The variable, is p, not *p. p points to a new piece of memory that stores the address of a.

About int**

1
int** q = &p;

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"; // exactly same as 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]); // pca[0] == s1 == the address of 'C'
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