blob: 2493f1a68ef31f9b690a981fa5ba44d7e7586b59 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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;
}
|