Создать простой список из строк - C (СИ)
Формулировка задачи:
Пытаюсь создать простенький список из строк. Не пашет.
Что я делаю не так?
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <malloc.h>
#define m 51
struct sent{
char *str;
struct sent *next;
};
void create_node (struct sent *h, char *info){
struct sent *n/* = malloc (sizeof(struct sent))*/;
if (h == NULL) h->next = n;
else {
n = h;
while (n != NULL) n = n->next;
}
// n = realloc (n, sizeof(sent)*(1 + strlen (info)));
n->str = strdup (info);
}
char dialog (struct sent *h, char* str){
char d;
if (h != NULL)
printf ("Proceed? (y/n)\n");
create_node (h, str);
d = getch();
return d;
}
void clr_mem (struct sent *h){
struct sent *tmp;
while (h != NULL) {
tmp = h;
h = h->next;
free (tmp);
}
}
int main () {
struct sent *head = NULL;
char c = 'y';
char *s = malloc (m);
printf("Put some text here: \n");
while (c == 'y') {
scanf ("%s", s);
c = dialog (head, s);
}
clr_mem (head);
getch ();
return 0;
}Решение задачи: «Создать простой список из строк»
textual
Листинг программы
/*...*/
struct sent
{
char* str;
struct sent* next;
};
void create_node(struct sent** h, char* info)
{
/*...*/
n->str = strdup(info);
/*...*/
}
/*...*/
void clr_mem(struct sent* h)
{
struct sent* tmp;
while (h != NULL)
{
tmp = h;
h = h->next;
free(tmp);
}
}
/*...*/
Объяснение кода листинга программы
- Структура
sentобъявлена с полямиstrиnext. - Функция
create_nodeпринимает указатель на голову списка и строку. Создает новый узел, указывает на негоnextпредыдущего узла и сохраняет строку в новом узле. - Функция
clr_memпринимает указатель на голову списка и освобождает память, начиная с первого узла и до последнего.