The problem is I use malloc in the last function(toString()).
I just wanna know if there is anyway to free it? or that I dont have to?
Thanks
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
/* Function prototypes */
void process(char input);
void update(char words[][51], int position);
char * toString(char character);
/* the global variables */
char words[100][51]; //the array of the words inside the text
int lastWordPos = 0; //position of the last word in array words
/* Main Function */
int main()
{
char character = getchar(); //get a character from stdin
char tempWord[51] = ""; //temporary array for storing a word
char tempDigit[51] = ""; //temporary array for storing a number
while(character != '0') //as long as the character from stdin is not 0, keep looping
{
//if the character is an alphabet
if(isalpha(character))
{
while( isalpha(character) )
{
strcat(tempWord, toString(character)); //get the whole word
character = getchar();
}
strcpy(words[lastWordPos], tempWord); //add the word to the word list
printf("%s", tempWord); //print the word
strcpy(tempWord, ""); //reset tempWord, so that it can be used again at the next loops, if needed
lastWordPos++; //increment the position of the word list
}
//if the character is a number
if(isdigit(character))
{
while( isdigit(character) )
{
strcat(tempDigit, toString(character)); //get the whole number
character = getchar();
}
int position = lastWordPos - atoi(tempDigit); //get the position of the word that will replace the number
printf("%s", words[position]); //print the word
strcpy(tempDigit, ""); //reset tempDigit, so that it can be used again at the next loops, if needed
update(words, position); //update the list of words
}
//if the character is a punctuation of a white space, print it
if(ispunct(character) || isspace(character)) printf("%c", character);
//get next character from stdin
character = getchar();
}
return 0;
}
/* update : take an array of characters and a position of the word that wants to be put at front of the list
* Input: a char array and position of the word
* Output: the word at the position of the array is put on front, returns void
*/
void update(char words[][51], int position)
{
int i;
char temp[51];
for(i=position; i<lastWordPos-1; i++) //will keep swapping to move the word from position to the front of the array
{
strcpy(temp, words[i]);
strcpy(words[i], words[i+1]);
strcpy(words[i+1], temp);
}
}
/* toString: take a character and make it into a type string( array of chars)
* Input: take a character
* Output: an pointer to an array of only 1 character long, that had been declared globally before
*/
char * toString(char character)
{
char *x = malloc(2 * sizeof(*x));
x[0] = character; //put a character inside the first index
return x; //return the address of the array of only one character
}