Recently I have started learning C++ and I decided to learn C along the way to improve my understanding of how computers work. For C I am using "The C Programming Language Book" by Brian Kernighan and Dennis Ritchie.
The exercise in question is to print all input lines disregarding trailing whitespace and empty lines.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_BLANKS 5
int main()
{
int c; /*holds current char to be printed*/
int* wsbuffer; /*buffer to hold possible trailing whitespace*/
int buffer_size; /*size of wsbuffer*/
int nws; /*number of whitespaces in buffer*/
int nonempty; /*0 if current line is empty, 1 else*/
int i; /*for loop*/
nonempty = nws = 0;
buffer_size = MAX_BLANKS;
wsbuffer = (int*) malloc(buffer_size*sizeof(int));
while (EOF != (c=getchar()))
{
if (c==' ' || c=='\t')
{
++nws;
if (nws>buffer_size)
{
buffer_size *=2;
wsbuffer = (int*) realloc(wsbuffer,buffer_size*sizeof(int));
}
wsbuffer[nws-1] = c;
}
else if (c=='\n')
{
if (nonempty==1) {
putchar(c);
nws = nonempty = 0;
}
}
else
{
nonempty = 1;
for (i=0;i<nws;++i)
putchar(wsbuffer[i]);
nws = 0;
putchar(c);
}
}
free(wsbuffer);
return 0;
}
I compiled this using gcc -std=c90 -Wall -Wextra -pedantic
to adhere to the ISO protocol used by the book. It compiled fine with no warnings.
I deliberately set MAX_BLANKS
to 5
to test the code. I tested a few cases (empty lines, lines with only space, spaces at first etc) and the result seemed okay.
Since memory allocation is not yet covered in the book, I'd particularly like it if someone could take a look and let me know if I have any issues particularly with memory leaking or something. Of course, any other suggestions or improvements would be welcome!