【发布时间】:2018-12-18 09:03:51
【问题描述】:
我想阅读短语,直到我输入 Ctrl + Z 然后显示它们。我写了一个代码,但是在我输入一个短语后,它会显示该短语并退出。另外,我想动态分配内存。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char words[100],
**phrases,
**aux;
int c = 0;
phrases = (char **)malloc(1 * sizeof(char *));
if (phrases == NULL) exit(1);
aux = (char **)malloc(1 * sizeof(char *));
if (aux == NULL) exit(1);
do {
printf("Enter phrase: ");
fgets(words, 100, stdin);
aux[c] = (char *)malloc(strlen(words) * sizeof(char));
if (aux[c] == NULL) exit(1);
phrases[c] = aux[c];
strcpy(phrases[c], words);
c++;
aux = (char **)realloc(phrases, (c + 1) * sizeof(char *));
if (aux == NULL) exit(1);
phrases = aux;
} while (strcmp(phrases, "^Z") == 0);
for (int i = 0; i < c; i++) {
fputs(phrases[i], stdout);
printf("\n");
}
for (int i = 0; i < c; i++) free (phrases[i]);
free (phrases);
return 0;
}
你能告诉我我做错了什么以及应该怎么做吗?
【问题讨论】:
-
捕捉 SIGSTOP 信号
-
您使用的是 Windows 还是 Linux,因为答案因操作系统而异。
-
@user3386109 窗口
-
@kiranBiradar 我 99.99% 确信这不是这样做的方法。我只是尝试输入 CTRL+Z 并显示“^Z”所以我想我可以将它与它进行比较。
-
CTRL-Z 在标准输入上导致文件结束条件。您可以通过检查来自
fgets的返回值来检测这一点。fgets到达文件末尾时将返回 NULL。
标签: c string memory-management