Read and Store Strings Interactively using the malloc() function - C String

C examples for String:char array

Description

Read and Store Strings Interactively using the malloc() function

Demo Code

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

int main()//www .  j av a2 s. co m
{
     char *friends[5], *ptr, name[30];
     int length;
    
     for(int i = 0; i < 5; i++) {
          printf("Enter name of friend no. %d: ", i + 1);
          scanf(" %[^\n]", name);
          length = strlen(name);
          ptr = (char *) malloc (length + 1);
          strcpy(ptr, name);
          friends[i] = ptr;
     }
    
     printf("\n\nList of friends:\n");
     for(int i = 0; i < 5; i++)
         printf("Friend no. %d : %s\n", i+1, friends[i]);
    
      return(0);
}

Result


Related Tutorials