我在这个程序上遇到了几天的麻烦,我决定看看是否有人可以帮助我,或者给我一些提示,说明为什么它不起作用。我正在尝试做一个程序,将用户输入,然后将其打印回用户(我真的想做一种文本编辑器,但我一步一步做,以确保我理解所有的部分)。我没有给出最多的行,我希望用户能够写出他/她想要的那么多行,这就是为什么我使用malloc,然后realloc重新调整必要的内存:
我遇到的问题是它不会打印任何内容
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LEN 1000
int main(void)
{
int totalLines = 0;
char content[MAX_LEN + 1];
char **arrays;
int i = 0;
printf("Enter your text to be edited\n");
while (content[0] != '.') {
fgets(content, MAX_LEN, stdin);
content[strlen(content) - 1] = '\0';
arrays = malloc(sizeof(char *) * totalLines);
for (i = 0; i < totalLines; i++) {
arrays[i] = malloc(sizeof(char) * (strlen(content) + 1));
strcpy(arrays[i], content);
}
if (totalLines >= 1) {
arrays = realloc(arrays, sizeof(char *) * totalLines);
for (i = 0; i < totalLines; i++) {
arrays[i] = malloc(sizeof(char) * (strlen(content) + 1));
strcpy(arrays[i], content);
}
totalLines++;
}
}
/* after user presses '.' the following is excuted: */
for (i = 0; i < totalLines; i++) {
printf("%s", arrays[i]);
}
int k;
for (k = 0; k <= totalLines; k++) {
free(arrays[k]);
}
free(arrays);
arrays = NULL;
return 0;
}