Using Arrays of Pointers - C Pointer

C examples for Pointer:Array Pointer

Introduction

You can use an array of pointers to store references to the strings on the heap.

Here's how you might use this array of pointers:

Demo Code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define STR_COUNT  10                              // Number of string pointers

int main(void)
{
   const size_t BUF_SIZE = 100;                       // Input buffer size
   char buffer[BUF_SIZE];                             // A 100 byte input buffer
   char *pS[STR_COUNT] = { NULL };                      // Array of pointers
   size_t str_size = 0;/* ww  w  .j a  va2 s  . c  om*/

   for (size_t i = 0; i < STR_COUNT; ++i)
   {
      scanf("%s", buffer, BUF_SIZE);                 // Read a string
      str_size = strnlen(buffer, BUF_SIZE) + 1;      // Bytes required
      pS[i] = (char *)malloc(str_size);                        // Allocate space for the string
      if (!pS[i]) return 1;                             // Allocation failed so end
      strcpy(pS[i], buffer);               // Copy string to new memory
   }

   for (size_t i = 0; i < STR_COUNT; ++i)
   {
      free(pS[i]);
      pS[i] = NULL;
   }

   return 0;
}

Result


Related Tutorials