I am trying to learn C and have written a simple program that accepts the string from user and prints it. Would you loke to suggest me anything on my practices? I need to learn it very well. so please help me improving myself.
Here goes my code:
//Dynamic Array Allocation
#include <stdio.h> //this is a c code
#include <conio.h> //for using getch()
#include <stdlib.h> //for using malloc,realloc, and free
void createACopy(char * copyTo,char * copyFrom, int length) //creates copy
{
for(int i = 0; i < length; i++) //loof for 'length' times
{
copyTo[i] = copyFrom[i];
}
}
void main()
{
printf("Please enter a string\n");
char inputChar; //a characted input by user
int inputLength = 0; //holds the length of characters input so far
char * userInput; //a pointer that points to the beginnning of the user input
userInput = (char *)malloc(sizeof(char)); //dynamically assign a single character size memory to the pointer
if (userInput == NULL) //if malloc could not find sufficient memory
{
free (userInput); //free the memory
puts ("Error Allocating memory"); //print error message
exit (1); //exit the program
}
do{ //keep looping till the user hits 'Enter' key
inputChar = getch(); //get the character keyed in by user in inputChar variable
if(inputChar ==char(8)) //if user hits backspace
{
inputLength--; //decrease the length of user input by 1
continue; //continue and look for next character
}
char * storeOldInputHere = (char *) malloc(inputLength+1); //dynamically find a memory location of size 'inputLenght'
if (storeOldInputHere == NULL) //if malloc could not find sufficient memory
{
free (storeOldInputHere);
puts ("Error Allocating memory for copying the old input");
exit (1);
}
createACopy(storeOldInputHere,userInput,inputLength); //store the old Input here because realloc might give us a different location altogether.
userInput = (char *) realloc(userInput,inputLength+2); //now after we got a new character, reallocate memory.
if (userInput == NULL) //if realloc could not find sufficient memory
{
free (userInput);
puts ("Error Reallocating memory");
exit (1);
}
createACopy(userInput, storeOldInputHere,inputLength); //Copy back the original input string to the newly allocated space again.
userInput[inputLength] = inputChar; //append the new character user inserted.
free (storeOldInputHere); //free the storeOldInputHere
inputLength ++; //increment the length counter by 1
}while(inputChar != char(13)); //keep looping untill user hits 'Enter' key
userInput[inputLength] = '\0'; //append a null charater at the end of the string
printf("\nyou entered %d characters",inputLength);
printf("\nyou entered: %s\n",userInput);
free(userInput); //free the userInput
}
Thanks in Advance