Write a program as follows Define a pointer to character nam
Write a program as follows.
Define a pointer to character, named cp. Next, use malloc() to allocate enough memory to hold 26 characters (For this, you should assign the return value of malloc() to cp). Assign english alphabets ‘a’ to ‘z’ (lowercase) as characters to the allocated space. Next, print the content of those memory location to show those alphabets. Next, use free() to free the allocated memory.
In the same program, use the same operations, i.e., applying malloc() and free() on cp, but this time by allocating 10 bytes to hold characters ‘0’ to ‘9’.
Note: do not forget to include <stdlib.h>
Can somebody please help me and solve this problem? Thank you.
Solution
#include<stdlib.h>
 #include<stdio.h>
 //Main Function
 int main()
 {
 //void * malloc (size_t size);
 //Character type pointer declared
 char *cp;
 //Loop counter
 int c;
 //Allocates 26 bytes to store a - z using malloc
 cp = (char *) malloc(sizeof(char) * 26);
 //Accept 26 alphabets
 printf(\"\  Enter the alphabets a - z (lowercase): \");
 for(c = 0; c < 26; c++)
 {
 fflush(stdin);
 scanf(\"%c\", (cp + c));
 }
 //Displays 26 alphabets
 printf(\"\  Pointer contains a - z (lowercase): \");
 for(c = 0; c < 26; c++)
 {
 printf(\"%c \", *(cp + c));
 }
 //Free the memory
 free(cp);
 //Allocates 10 bytes of memory to store 0 - 9 using malloc
 cp = (char *) malloc(sizeof(char) * 10);
 //Accepts data
 printf(\"\  Enter the alphabets 0 - 9: \");
 for(c = 0; c < 10; c++)
 {
 fflush(stdin);
 scanf(\"%c\", (cp + c));
 }
 //Displays data
 printf(\"\  Pointer contains 0 - 9: \");
 for(c = 0; c < 10; c++)
 {
 printf(\"%c \", *(cp + c));
 }
 //Release memory using free
 free(cp);
 }
Output:
 Enter the alphabets a - z (lowercase): a
 b
 c
 d
 e
 f
 g
 h
 i
 j
 k
 l
 m
 n
 o
 p
 q
 r
 s
 t
 u
 v
 w
 x
 y
 z
Pointer contains a - z (lowercase): a b c d e f g h i j k l m n o p q r s t u v w x y z
 Enter the alphabets 0 - 9: 0
 1
 2
 3
 4
 5
 6
 7
 8
 9
Pointer contains 0 - 9: 0 1 2 3 4 5 6 7 8 9


