Use malloc() to allocate storage space for string data. - C Memory

C examples for Memory:malloc

Description

Use malloc() to allocate storage space for string data.

Demo Code

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

int main( void )
{
   char count, *ptr, *p;

   ptr = (char *)malloc(35 * sizeof(char));

   if (ptr == NULL){
       puts("Memory allocation error.");
       return 1;/*from w w w  .  j a  va 2s  .c om*/
   }

   /* Fill the string with values 65 through 90, */
   /* which are the ASCII codes for A-Z. */

   p = ptr;

   for (count = 65; count < 91 ; count++)
       *p++ = count;

   *p = '\0';/* Add the terminating null character. */

   puts(ptr);

   free(ptr);

   return 0;
}

Result


Related Tutorials