Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *p = NULL;
char linha[100];
char **strings = NULL;
int c = 0;
int nstrings = 0;
int maxstrings = 0;
void *temp = NULL;
for (;;) {
printf("Type something or exit to exit: ");
if (fgets(linha, sizeof(linha), stdin) == NULL)
break;
if ((p = strchr(linha, '\n')) != NULL)
*p = '\0';
else
while ((c = getchar()) != '\n' && c != EOF);
if (strcmp(linha, "exit") == 0)
break;
if (nstrings == maxstrings)
temp = realloc(strings, (maxstrings + 10) * sizeof(*strings));
if (temp) {
strings = temp;
maxstrings += 10;
}
else
break;
p = malloc(strlen(linha) + 1);
if (p)
strcpy(p, linha);
else
break;
strings[nstrings++] = p;
}
--nstrings;
for (; nstrings >= 0; nstrings--) {
printf("%s\n", strings[nstrings]);
free(strings[nstrings]);
}
free(strings);
return 0;
}
Just for testing purposes, I entered all the letters of the alphabet, one letter per line. Here's my output:
Code:
Type something or exit to exit: a
Type something or exit to exit: b
Type something or exit to exit: c
Type something or exit to exit: d
Type something or exit to exit: e
Type something or exit to exit: f
Type something or exit to exit: g
Type something or exit to exit: h
Type something or exit to exit: i
Type something or exit to exit: j
Type something or exit to exit: k
Type something or exit to exit: l
Type something or exit to exit: m
Type something or exit to exit: n
Type something or exit to exit: o
Type something or exit to exit: p
Type something or exit to exit: q
Type something or exit to exit: r
Type something or exit to exit: s
Type something or exit to exit: t
Type something or exit to exit: u
Type something or exit to exit: v
Type something or exit to exit: w
Type something or exit to exit: x
Type something or exit to exit: y
Type something or exit to exit: z
Type something or exit to exit: exit
z
y
x
w
v
u
t
s
r
q
p
o
n
m
l
k
j
i
h
g
f
e
d
c
A little window pops-up asking if I want to send the error to Microsoft. I can't see the error but I think it has something to do with memory freeing. Can someone help me find the problem, please?