Handling Strings Using Pointers - C String

C examples for String:char array

Description

Handling Strings Using Pointers

Demo Code

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

int main(void)
{
   const size_t BUF_SIZE = 100;                     // Input buffer size
   char buffer[BUF_SIZE];                           // A 100 byte input buffer
   scanf("%s", buffer, BUF_SIZE);                 // Read a string

   int length = strnlen(buffer, BUF_SIZE) + 1;
   char *pString =(char*) malloc(length);

   if (!pString) {
      printf("Memory allocation failed.\n");
      return 1;/*w  w w . java 2  s  . co m*/
   }

   strcpy(pString, buffer);               // Copy string to new memory
   printf("%s", pString);
   free(pString);
   pString = NULL;

   return 0;
}

Result


Related Tutorials