summaryrefslogtreecommitdiffstats
path: root/main.c
diff options
context:
space:
mode:
Diffstat (limited to 'main.c')
-rw-r--r--main.c54
1 files changed, 54 insertions, 0 deletions
diff --git a/main.c b/main.c
new file mode 100644
index 0000000..2493f1a
--- /dev/null
+++ b/main.c
@@ -0,0 +1,54 @@
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#define MAXLINE 256
+
+char *reverse(char *input)
+{
+unsigned short i = 0;
+int length = strlen(input)-2;//length of char array minus NULL and newline
+char *output = malloc(sizeof(char)*length+2);//dynamically allocate the char array
+if (!output){printf("Malloc failed!\n"); exit(1);}
+
+ while (length != -1)//reverse the string
+ {
+ output[i] = input[length];//last char of input = first char of output
+ ++i;//increment the output
+ --length;//deincrement the input
+ }
+output[i] = '\0';//null terminate the reversed string
+return output;
+}
+
+int main(void)
+{
+char buff;//for holding the char just read
+unsigned short maxline = MAXLINE;//length to malloc by default
+char *array=malloc(sizeof(char)*maxline);//allocate heap memory
+if (!array){printf("Malloc failed!\n"); exit(1);}//exit if out of memory
+
+unsigned short length = 0;//length of read string
+while ((buff = getchar()) != EOF)//read char by char from newline into buff until a EOF is inputted
+{
+
+if (length == maxline){maxline+=20; array=realloc(array,sizeof(char)*maxline); if (!array){printf("Realloc failed!"); exit(1);}}//realloc the array to allow for more chars if needed
+
+array[length] = buff;//write the char to the array
+if (buff == '\n')//if there's a newline, process the string of chars read
+ {
+ if (length == 0){length=0; goto skip;}//Don't bother to reverse a string containing just a newline
+ array[length+1] = '\0';//add a null terminator to the string
+ char *reversed = reverse(array);//reverse the string and return a pointer to the reversed string
+ printf("Reversed: %s\n", reversed);//print the reversed string
+ free(reversed);//free the malloced memory, to stop memory leaking
+ length = 0;//reset length back to 0 ready for a new string
+ goto skip;
+ }
+
+++length;
+skip: ;
+}
+free(array);//free pointer like a good boy
+return 0;
+}