I'm a student learning to code in C. I had to make a program for class to reverse lines of input from the keyboard (not character wise, but reverse the order of the lines input).
The program is working to the requirements of the assignment already, but feel free to have a look at my code and help me understand where I can make improvements to it. I am looking to learn as much as possible about the language.
Assignment:
Program will allow user to type in several lines of a poem. User signals the end of their input with a single dot on a newline (and enter). After input, the lines will be printed out from last entered to first. No line can be greater than 1000 characters in length. No max number of lines. Lines cannot contain a single '.' dot/period as the only character on the line. No use of global variables.
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 int main(){
6
7 /* array variables */
8 int MAXSIZE = 1000;
9 char **array;
10 char *string;
11 char inputStr[MAXSIZE+1];
12
13 /* declare for my while loop parameter*/
14 inputStr[0] = 0;
15
16 /* logic variables */
17 int i = 0;
18 int j = 0;
19
20 /* allocate inital space for a line */
21 array = malloc(sizeof(char*) * 1);
22
23 printf("Enter the poem:\n");
24
25 /* if the line is only a period, end loop */
26 while(*inputStr != '.'){
27
28 /* get input from user, max 1000 chars per line */
29 fgets(inputStr,MAXSIZE,stdin);
30 inputStr[strlen(inputStr)-1] = '\0';
31
32 if(*inputStr != '.'){
33
34 /* allocate space to store the string and copy from input */
35 string = malloc ( sizeof(char) * (strlen(inputStr)+1) );
36 strncpy ( string, inputStr, strlen(inputStr)+1 );
37
38 /* allocate space in the array for the string and copy it in */
39 array[i] = malloc((sizeof(char*))*(strlen(string))+1);
40 strncpy(array[i],string,strlen(string)+1);
41
42 /* free the string, add to line count, reallocate with new line count */
43 free (string);
44 i++;
45 array = realloc(array, (i + 1) * sizeof(char*));
46 }
47 }
48
49 /* print the array in reverse order using line count*/
50 for( j = i-1 ; j >= 0; j-- ){
51 printf("%s\n", array[j]);
52 }
53
54 /* free the array strings and then the array */
55 while(i--){
56 free(array[i]);
57 }
58 free(array);
59
60 return(0);
61
62 }