Mega Code Archive

 
Categories / C / Code Snippets
 

Allocate memory block how to use malloc

#include <stdio.h> #include <stdlib.h> int main () { int i, j; char *str; printf ("String Length? "); scanf ("%d", &i); str = (char*) malloc (i+1); if (str == NULL) exit (1); for ( j = 0; j < i; j++) str[j] = rand() % 26 + 'a'; str[i] = '\0'; printf ("Random string: %s\j", str); free (str); return 0; }