C Exercise Example 77

100 Classic C Examples

Title:Practice pointer-to-pointer (using multi-level pointers to traverse a string array).

Program analysis:None.

Program source code:

Example

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. 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 a pointer to pointer for (k = 0; k < 5; k++) { q = &s[k]; // make pointer q point to the address of the kth element in the character pointer array printf("%s\n", *q); // dereference q to output the corresponding string } return 0; }

Code explanation:

  • pointer to pointer exercise:qis defined asconst char **type, it is a pointer toconst char *pointer. By passing theqassign to&s[k],qpoints to an array of character pointerssin thekaddress of the element.

  • q = &s[k]role of:s[k]is the ...th in the character pointer arraykelement,&s[k]represents thekaddress of the element. Therefore,qIt ultimately points to an element in an array of character pointers.

  • printf("%s\n", *q)role of:*qdereferenceq, i.e., obtains[k]Then print out the content of the string it points to.

The output of the above example is:

man
woman
girl
boy
sister

100 Classic C Examples

other extensions