I'm self-learning C and I came across a problem where lines need to be sorted according to their lengths. This portion stores characters from the input stream into an array and puts each lines in an array of pointers. Then tries to print the first line.
#include <stdio.h>
#include <string.h>
#define LINES 5
void main()
{
char c;
char* str1 = (char*)malloc(30);
char* str[LINES];
int i = 0,temp;
while ((c = getchar()) != EOF) //storing all characters from input stream into an array
*(str1 + i++) = c;
*(str1 + i) = '\0';
temp = i;//total number of characters
i = 0;
int j = 0, k = 0;
str[j] = (char*)malloc(30);
while (i < temp)//storing each line in separate pointers of the array of pointers
{
if (j + 1 == LINES)
break;
if (*(str1 + i) == '\n')
{
*(*(str + k) + j++) = '\0';
str[j] = (char*) malloc(30);
k = 0;
}
else
*(*(str + k++) + j) = *(str1 + i);
i++;
}
printf("%s\n", str[0]);//printing the first line
}
This is what my output screen looks like:
iiii
iii
ii
i
i
^Z
Press any key to continue . . .
In the input screen after giving the input and entering EOF the program crashes. Why is it not working?
btw it crashes after EOF.