C Exercise 77
100 Classic C Language Examples
**Problem:** Practice pointers to pointers (using multi-level pointers to traverse an array of strings).
**Analysis:** None.
Program source code:
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
#include
<
stdio.h
#include
<
stdlib.h
int
main
(
)
{// Define an array of character pointers to store string constants
const
char
s
[
]
=
{
"
man
"
,
"
woman
"
,
"
girl
"
,
"
boy
"
,
"
sister
"
}
;
// Define a pointer variable that points to a character pointer
const
char
**
q
;
int
k
;
// Traverse the array and output each string through the pointer-to-pointer
for
(
k
=
0
;
k
<
5
;
k
++
)
{
q
= &
s
[
k
]
;
// Make pointer q point to the address of the k-th element in the character pointer array
printf
(
"
%s
\
n
"
, *
q
)
;
// Dereference q to output the corresponding string
}
return
0
;
}
Code explanation:
-
Pointer-to-pointer practice:
qis defined asconst char **type; it is a pointer toconst char *. By makingqto&s[k],qpoint to the character pointer arraysthekth element's address. -
q = &s[k]The Role of:s[k]is thekth element in the character pointer array,&s[k]represents thekth element's address. Therefore,qit ultimately points to an element in the character pointer array. -
printf("%s\n", *q)The Role of:*qDereferencingq, that is, obtainings[k]the string content it points to, and then printing it out.
The above example produces the following output:
man
woman
girl
boy
sister