我正在自学 C,我遇到了一个问题,即需要根据行的长度对行进行排序。这部分将输入流中的字符存储到一个数组中,并将每一行放入一个指针数组中。然后尝试打印第一行。
#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
}
这是我的输出屏幕的样子:
iiii
iii
ii
i
i
^Z
Press any key to continue . . .
在给出输入并输入 EOF 后的输入屏幕中,程序崩溃。为什么它不起作用?
顺便说一句,它在 EOF 之后崩溃。