#include <stdio.h>
#include <stdlib.h>
struct treeNode
{
char *word;
int NumberCnt;
struct treeNode *rightPTR, *leftPTR;
};
typedef struct treeNode node;
node *rootPTR = NULL;
void freeTree(node *currPTR)
{
if (currPTR!= NULL)
{
freeTree(currPTR -> leftPTR);
free(currPTR);
freeTree(currPTR -> rightPTR);
}
}
void printTree(node *currPTR)
{
if (currPTR != NULL)
{
printTree(currPTR ->leftPTR);
printf("%s appeared:%d times\n", currPTR->word, currPTR->NumberCnt);
printTree(currPTR ->rightPTR);
}
}
int insertNode (char* input)
{
node *tempPTR = malloc(sizeof(node));
tempPTR -> word = input;
tempPTR -> NumberCnt=0;
tempPTR -> leftPTR = NULL;
tempPTR -> rightPTR = NULL;
if (rootPTR == NULL)
{
rootPTR = tempPTR;
rootPTR -> NumberCnt++;
}
else
{
node *currPTR = rootPTR;
node *prevPTR = NULL;
while (currPTR != NULL)
{
int comp = strcmp(input, (currPTR->word));
if (comp == 0)
{
printf ("Entry already exists\n");
currPTR->NumberCnt++;
return 1;
}
else if (comp < 0)
{
prevPTR = currPTR;
currPTR = currPTR->leftPTR;
}
else if (comp > 0)
{
prevPTR = currPTR;
currPTR = currPTR->rightPTR;
}
}
int comp = strcmp(input, (prevPTR ->word));
if (comp < 0)
{
prevPTR->leftPTR = tempPTR;
prevPTR ->NumberCnt++;
}
else if (comp > 0)
{
prevPTR->rightPTR = tempPTR;
prevPTR->NumberCnt++;
}
return 0;
}
printf("root1%s\n",rootPTR->word);
return 2;
}
int search(char* input)
{
if (input == rootPTR ->word)
{
printf("Node found %s\n", rootPTR->word);
return 0;
}
else
{
if (input < rootPTR ->word)
{
node *currPTR = rootPTR->leftPTR;
while (currPTR != NULL)
{
if (input == currPTR->word)
{
printf("Node found %s\n", currPTR->word);
return 0;
}
else if (input < currPTR->word)
{
currPTR = (currPTR -> leftPTR);
}
else if (input > currPTR->word)
{
currPTR = (currPTR -> rightPTR);
}
}
printf ("Node not in tree\n");
return 1;
}
if (input > rootPTR ->word)
{
node *currPTR = rootPTR->rightPTR;
while (currPTR != NULL)
{
if (input == currPTR->word)
{
printf ("Node found %s\n", currPTR->word);
return 0;
}
else if (input < currPTR->word)
{
currPTR = (currPTR -> leftPTR);
}
else if (input > currPTR->word)
{
currPTR = (currPTR ->rightPTR);
}
}
printf ("Node not in tree\n");
return 1;
}
}
return 2;
}
void fixWord(char* buff)
{
char* unfixed = buff;
char* fixed = buff;
while (*unfixed)
{
if (isalpha(*unfixed))
{
*fixed=tolower(*unfixed);
*fixed++;
}
*unfixed++;
}
*fixed=0;
}
int main()
{
FILE *ptr_file;
char buff [100];
//ptr_file = fopen ("sherlock.txt", "r");
ptr_file = fopen ("input.txt", "r");
if (!ptr_file)
printf("File read error");
while(fscanf(ptr_file, "%s ", buff ) != EOF)
{
int comparison = strcmp(buff, "endoffile");
if (comparison == 0)
{
return 0;
}
fixWord(buff);
insertNode(buff);
}
fclose(ptr_file);
printf("root:%s\n", rootPTR->word);
return 0;
}
Ok I have this binary tree which is taking string inputs from a file. It works if I pass strings directly to the tree, however when I attempt to pass it the strings I read in form the file it keeps on replacing the root node and does not add them correctly to the tree.
buff is current line value and overwritten on each line reading:
insertNode(buff);
insertNode assigns overwriten buffer.
int insertNode (char* input)
{
node *tempPTR = malloc(sizeof(node));
tempPTR -> word = input;
....
So, you should dynamic allocation for input value as:
int insertNode (char* input)
{
node *tempPTR = malloc(sizeof(node));
tempPTR -> word = strdup(input);
....
You're passing buff to your insert function, and it's storing that in the node. So all your nodes will end up pointing to the same address, that of buff in main.
You need to allocate storage for each string in each node, and copy your input into that. And remember to deallocate properly when you delete your tree.
strdup can be handy for that if your library has it.
Related
I am working on building circular doubly linked list code.
In my code, there are four function- add node, delete node, print clockwise, print counterclockwise. All my code works fine, besides the delete function. The if(recycle->name == x) line seems not working properly, and free(recycle) also doesn't successfully free the recycle node.
My original code are. as follows
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define nameLen 20
struct Node
{
char name[nameLen];
struct Node *left; //next
struct Node *right; //previous
};
struct Node* current;
struct Node* head;
int count = 0;
struct Node* GetNewNode(char *x)
{
struct Node* newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
strncpy(newNode->name, x, nameLen);
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void add_name(char *x)
{
struct Node* temp = current;
struct Node* newNode = GetNewNode(x);
count++;
if(current == NULL)
{
current = newNode;
head = current;
}
else
{
current->left = newNode;
newNode->right = temp;
current = newNode;
current->left = head;
head->right = current;
}
printf("Add %s into database.\n\n", current->name);
}
void delete_name(char *x)
{
int i, j;
struct Node* recycle = current;
if(current == NULL)
{
printf("No data input.");
}
else
{
for (i = 0; i < count; i++)
{
if(recycle->name == x)
{
free(recycle);
j++;
printf("Delete %s from database.\n", x);
}
recycle = recycle->left;
}
if(j == 0)
{
printf("There is no %s in data", x);
}
current = recycle;
}
}
void print_clock(int number)
{
int i;
struct Node* temp = current;
if(temp == NULL)
{
printf("No data input.");
}
else
{
printf("Clockwise: \n");
for(i = 0; i < number; i++)
{
printf("%s ",temp->name);
temp = temp->left;
}
}
printf("\n\n");
}
void print_counter(int number)
{
int i;
struct Node* temp = current;
if(temp == NULL)
{
printf("No data input.");
}
else
{
printf("Counterclockwise: \n");
for(i = 0; i < number; i++)
{
printf("%s ",temp->name);
temp = temp->right;
}
}
printf("\n\n");
}
int main()
{
char s1;
char s2[nameLen];
char name[nameLen];
int number;
while(1)
{
printf("Enter the instruction: ");
scanf("%s %s", &s1, s2);
if (s1 == '+' && sscanf(s2, "%d", &number) == 1)
{
printf("Print out %d name(s) clockwise.\n", number);
print_clock(number);
}
else if (s1 == '-' && sscanf(s2, "%d", &number) == 1)
{
printf("Print out %d name(s) counterclockwise.\n", number);
print_counter(number);
}
else if (s1 == '+' && sscanf(s2, "%s", name) == 1)
{
add_name(s2);
}
else if (s1 == '-' && sscanf(s2, "%s", name) == 1)
{
delete_name(s2);
}
else if (s1 == 'e')
{
printf("Bye.\n");
break;
}
else // No match.
printf("Wrong Input. %s %s\n", &s1, s2);
}
system("pause");
return 0;
}
Statement recycle->name == x checks if two pointers point to the same object in memory. It does not check if two (different) objects in memory have equal content.
Use
if (strcmp(recycle->name, x) == 0) { ...
to check for equal string contents.
I'm getting segmentation fault when trying to access current_nap->next (sometimes even on current->value->napok but that's rare). I don't get why this happens because I can iterate through NapList with the functions in its header without any problem. Could you help me, please?
Here is my code:
void saveToFile()
{
int g;
g = open("save.dat", O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
JelentkezesList *current = jelentkezesek;
char line[] = "";
while (current != NULL)
{
printf("eddig ok\n");
strncpy(line, "", sizeof(line));
printf("eddig ok2\n");
strcat(line, "{");
strcat(line, current->value->nev);
strcat(line, ";");
strcat(line, current->value->cim);
strcat(line, ";");
printf("eddig ok3\n");
NapList *current_nap = current->value->napok;
printf("eddig ok4\n");
while (current_nap != NULL)
{
printf("eddig ok5\n");
if (current_nap->value == HETFO)
{
strcat(line, "0");
printf("hetfo\n");
}
else if (current_nap->value == KEDD)
{
strcat(line, "1");
printf("kedd\n");
}
else if (current_nap->value == SZERDA)
{
strcat(line, "2");
printf("szerda\n");
}
else if (current_nap->value == CSUTORTOK)
{
strcat(line, "3");
printf("csutortok\n");
}
else if (current_nap->value == PENTEK)
{
strcat(line, "4");
printf("pentek\n");
}
else if (current_nap->value == SZOMBAT)
{
strcat(line, "5");
printf("szombat\n");
}
else if (current_nap->value == VASARNAP)
{
strcat(line, "6");
printf("vasarnap\n");
}
printf("eddig ok5.1\n");
//if (current_nap->next != NULL)
//{
strcat(line, ",");
//}
printf("eddig ok6\n");
current_nap = current_nap->next;
printf("eddig ok7\n");
}
strcat(line, "}\n");
if (write(g, line, sizeof(line)) != sizeof(line))
{
printf("Hiba a mentés során!");
exit(1);
}
printf("eddig ok8\n");
current = current->next;
printf("eddig ok9\n");
}
close(g);
printf("%s", "Sikeres mentés!");
}
Here are my headers:
JelentkezesList
#include "string_utils.h"
#include "jelentkezes.h"
#include "nap_list.h"
#ifndef JELENTKEZES_LIST_H
#define JELENTKEZES_LIST_H
typedef struct jelentkezes_node
{
Jelentkezes *value;
struct jelentkezes_node *next;
} JelentkezesList;
void printJelentkezesList(JelentkezesList *head)
{
JelentkezesList *current = head;
while (current != NULL)
{
printf("\n");
printJelentkezes(current->value);
current = current->next;
}
}
void printJelentkezesListForDay(JelentkezesList *head, Nap nap)
{
JelentkezesList *current = head;
while (current != NULL)
{
if (containsNap(current->value->napok, nap))
{
printf("\n");
printJelentkezes(current->value);
}
current = current->next;
}
}
void addToJelentkezesList(JelentkezesList **list, Jelentkezes *value)
{
JelentkezesList *current = *list;
if (current == NULL)
{
current = (JelentkezesList *)malloc(sizeof(JelentkezesList));
Jelentkezes *j = value;
j->azonosito = 0;
current->value = j;
current->next = NULL;
*list = current;
}
else
{
while (current->next != NULL)
{
current = current->next;
}
current->next = (JelentkezesList *)malloc(sizeof(JelentkezesList));
Jelentkezes *j = value;
j->azonosito = current->value->azonosito + 1;
current->next->value = j;
current->next->next = NULL;
}
}
Jelentkezes *findJelentkezes(JelentkezesList *list, int id)
{
Jelentkezes *result = NULL;
JelentkezesList *current = list;
while (current != NULL && result == NULL)
{
if (current->value->azonosito == id)
{
result = current->value;
}
current = current->next;
}
return result;
}
void deleteJelentkezes(JelentkezesList **list, Jelentkezes *j)
{
JelentkezesList *current = *list;
if (current->value->azonosito == j->azonosito)
{
*list = current->next;
free(current);
return;
}
while (current->next->value->azonosito != j->azonosito)
{
current = current->next;
}
JelentkezesList *toDelete = current->next;
current->next = current->next->next;
free(toDelete);
*list = current;
}
JelentkezesList *createJelentkezesList()
{
JelentkezesList *jelentkezes_head = NULL;
return jelentkezes_head;
}
#endif
Jelentkezes
#include "string_utils.h"
#include "nap.h"
#include "nap_list.h"
#include <stdio.h>
#include <string.h>
#ifndef JELENTKEZES_H
#define JELENTKEZES_H
typedef struct
{
int azonosito;
String nev;
String cim;
NapList *napok;
} Jelentkezes;
Jelentkezes *createJelentkezes(String *nev, String *cim, NapList *napok)
{
Jelentkezes *j = (Jelentkezes *)malloc(sizeof(Jelentkezes));
j->azonosito = -1;
j->nev = *nev;
j->cim = *cim;
j->napok = napok;
return j;
}
void printJelentkezes(Jelentkezes *j)
{
printf("Azonosító: %d\n", j->azonosito);
printf("Név: %s, Cím: %s\n", j->nev, j->cim);
printf("Munkavállalás napjai: ");
printNapList(j->napok);
}
#endif
NapList
#include "string_utils.h"
#include "nap.h"
#include <stdbool.h>
#ifndef NAP_LIST_H
#define NAP_LIST_H
typedef struct nap_node
{
Nap value;
struct nap_node *next;
} NapList;
void printNapList(NapList *head)
{
NapList *current = head;
while (current != NULL)
{
if (current->value == HETFO)
{
printf("hétfő");
}
else if (current->value == KEDD)
{
printf("kedd");
}
else if (current->value == SZERDA)
{
printf("szerda");
}
else if (current->value == CSUTORTOK)
{
printf("csütörtök");
}
else if (current->value == PENTEK)
{
printf("péntek");
}
else if (current->value == SZOMBAT)
{
printf("szombat");
}
else if (current->value == VASARNAP)
{
printf("vasárnap");
}
if (current->next != NULL)
{
printf(", ");
}
current = current->next;
}
printf("\n");
}
void addToNapList(NapList **list, Nap value)
{
NapList *current = *list;
if (current == NULL)
{
current = (NapList *)malloc(sizeof(NapList));
current->value = value;
current->next = NULL;
*list = current;
}
else
{
while (current->next != NULL)
{
current = current->next;
}
current->next = (NapList *)malloc(sizeof(NapList));
current->next->value = value;
current->next->next = NULL;
}
}
bool containsNap(NapList *nl, Nap nap)
{
NapList *current = nl;
while (current != NULL)
{
if (current->value == nap)
return true;
current = current->next;
}
return false;
}
NapList *createNapList()
{
NapList *nap_head = NULL;
return nap_head;
}
#endif
I tried to implement circular linked list to manage a set of tasks by a server side application. The application is multi-threaded where one thread (updater() ) reads the linked list only for read while another two (push_stream() and delete_stream()) access the linked list to add to and delete from the linked list respectively.
My problem is not all the files to be deleted (after being processed) are deleted.
struct data_stream
{
bool processed;
int count;
char filename[30];
int TYPE_GRP;
int task_type;
struct data_stream *next;
};
struct data_stream *stream_head=NULL; //global variable
main(partial code)
main()
{
_beginthread(updater, 0, NULL);
while ((new_socket = accept(srv_sock, (struct sockaddr *)&client, &c)) != INVALID_SOCKET)
{
_beginthreadex(0, 0, handle_client, &new_socket, 0, 0);
}
}
handle_client function (partial code)
handle_client()
{
//some where in handle_client
EnterCriticalSection(&stream_lock);
stream_head = push_stream(&stream_head, TYPE_GRP, task_type);
LeaveCriticalSection(&stream_lock);
}
updater function (full source code)
void updater(void *data)
{
while (1)
{
struct data_stream*temp = stream_head;
struct data_stream*first = stream_head;
struct data_stream*prev = NULL;
if (stream_head != NULL)
{
struct data_stream*next = NULL;
do
{
next = temp->next;
if (temp->processed == false&&temp->task_type == 2)
{
process_files(temp);
}
else if (temp->processed == false&&temp->task_type == 3)
{
process_others();
}
EnterCriticalSection(&stream_lock);
temp->processed = true;
LeaveCriticalSection(&stream_lock);
temp = next;
} while (temp != first);
}
if (stream_head != NULL)
{
EnterCriticalSection(&stream_lock);
stream_head=delete_stream(&stream_head);
LeaveCriticalSection(&stream_lock);
}
Sleep(6000);
}
}
process_files
void process_files(struct data_stream*temp)
{
int count = 0;
char file_to_update[50] = { NULL };
size_t name_len = strlen(temp->filename);
memcpy_s(file_to_update, name_len, temp->filename, name_len);
file_to_update[name_len] = '\0';
temp->count = 0;
FILE *list_to_update ;
fopen_s(&list_to_update , file_to_update, "r+b");
if (list_to_update != NULL)
{
char readline[100] = { '\0' };
while (fgets(readline, sizeof(readline), list_to_update ) != NULL)
{
//read a line at a time and process the list
count++;
}
temp->count = count;
fclose(list_to_update );
}
else
printf("\nerror opening file\n");
}
process_others()
void process_others(struct data_stream*temp)
{
int count = 0;
char file_to_update[50] = { NULL };
size_t name_len = strlen(temp->filename);
memcpy_s(file_to_update, name_len, temp->filename, name_len);
file_to_update[name_len] = '\0';
temp->count = 0;
FILE *list_to_update ;
fopen_s(&list_to_update , file_to_update, "r+b");
if (list_to_update != NULL)
{
char readline[100] = { '\0' };
while (fgets(readline, sizeof(readline), list_to_update ) != NULL)
{
//read a line at a time and process the list
count++;
}
temp->count = count;
fclose(list_to_update );
}
else
{
printf("\nerror opening file\n");
}
}
}
push_stream (full source code)
struct data_stream* push_stream(struct data_data_stream**head_ref, int typ_grp, int task_type)
{
struct data_stream*new_data_stream=
(struct data_data_stream*)malloc(sizeof(struct data_stream));
new_stream->processed = false;
new_stream->task_type = task_type;
new_stream->TYPE_GRP = typ_grp;
new_stream->filename[0] = NULL;
new_stream->count = 0;
new_stream->next = NULL;
if (task_type == 2)
sprintf_s(new_stream->filename, "%s%03d.txt", "file_md5_list_", stream_count);
else
sprintf_s(new_stream->filename, "%s%03d.txt", "other_list_", stream_count);
if (*head_ref == NULL)
{
*head_ref = new_stream;
new_stream->next = new_stream;
}
else
{
struct data_stream* last = (*head_ref)->next;
struct data_stream* prev = (*head_ref)->next;
while (last != *head_ref)
{
prev = last;
last = last->next;
}
new_stream->next = *head_ref;
last->next = new_stream;
}
if (stream_count > 998)
stream_count = 1;
else
stream_count++;
return new_stream;
}
delete_stream function (full source code)
struct data_stream* delete_stream(struct data_data_stream**head)
{
if (head == NULL)
return NULL;
struct data_stream*prev = NULL;
struct data_stream*temp = *head;
struct data_stream*first = *head;
do
{
struct data_stream*next = temp->next;
if (temp->processed)
{
if (prev == NULL)
*head = temp->next;
else
prev->next = temp->next;
char file_to_delete[50] = { NULL };
memcpy_s(file_to_delete, strlen(temp->filename), temp->filename, strlen(temp->filename));
DeleteFileA(file_to_delete);
free(temp);
}
else
{
prev = temp;
}
temp = next;
} while (temp != first);
if (prev == NULL)
{
return NULL;
}
return *head;
}
I am having trouble understanding what I should do in the AddNumber function of my program. When the AddNumber function is called in main a pointer variable previous is created, and it takes the user's input and points it at the address of the variable newNum. I created an if statement for it to do that, but I was informed it doesn't do anything.
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
typedef struct A_NewNumber{
struct A_NewNumber *next;
double newNum;
} NewNumber;
NewNumber *AddNumber(NewNumber *previous, char *input){
//char input[16];
//double numEntered = 0;
NewNumber *newNum = malloc(sizeof(NewNumber));
sscanf(input, "%lf", &newNum->newNum);
//sscanf(input, "%s", newNum->enterNumber);
//numEntered = atof(input);
/*if (previous != NULL){
previous->newNum;
}*/
newNum->next = NULL;
newNum->newNum = 0;
return newNum;
}
void PrintList(NewNumber *start){
NewNumber *currentNumber = start;
int count = 0;
while(currentNumber != NULL){
count++;
printf("Numbers:%lf\n",
currentNumber->newNum);
currentNumber = currentNumber->next;
}
printf("Total Numbers Entered%d\n", count);
}
void CleanUp(NewNumber *start){
NewNumber *freeMe = start;
NewNumber *holdMe = NULL;
while(freeMe != NULL){
holdMe = freeMe->next;
free(freeMe);
freeMe = holdMe;
}
}
int main(){
//indexNum = 0;
char command[16];
char input[16];
//float userInput;
NewNumber *userEnter = NULL;
NewNumber *start = NULL;
NewNumber *newest = NULL;
while(fgets(input, sizeof input, stdin)){
printf("Please enter a number->");
printf("Enter 'quit' to stop or 'print' to print/calculate");
sscanf(input, "%s", command);
if(newest == NULL){
start = AddNumber(NULL, input);
newest = start;
}else{
newest = AddNumber(newest, input);
}if(strncmp(command, "print", 5) == 0){
PrintList(start);
}else if(strncmp(command, "quit", 4)== 0){
printf("\n\nQuitting....\n");
break;
//userInput = enterNumber;
}
}
CleanUp(start);
return 0;
}
}
It was not that bad, was just in need of a bit of clean-up.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// ALL CHECKS OMMITTED!
typedef struct A_NewNumber {
struct A_NewNumber *next;
double newNum;
} NewNumber;
NewNumber *AddNumber(NewNumber * previous, char *input)
{
int res;
// allocate new node
NewNumber *newNum = malloc(sizeof(NewNumber));
if (newNum == NULL) {
fprintf(stderr, "Malloc failed in AddNUmber()\n");
return previous;
}
// convert input string to float
res = sscanf(input, "%lf", &newNum->newNum);
if (res != 1) {
fprintf(stderr, "Something bad happend in AddNUmber()\n");
return previous;
}
// terminate that node
newNum->next = NULL;
// if this is NOT the first node
// put new node to the end of the list
if (previous != NULL) {
previous->next = newNum;
}
// return pointer to new node at end of the list
return newNum;
}
void PrintList(NewNumber * start)
{
NewNumber *currentNumber = start;
int count = 0;
while (currentNumber != NULL) {
count++;
printf("Numbers:%lf\n", currentNumber->newNum);
currentNumber = currentNumber->next;
}
printf("Total Numbers Entered %d\n", count);
}
void CleanUp(NewNumber * start)
{
NewNumber *freeMe = start;
NewNumber *holdMe = NULL;
while (freeMe != NULL) {
holdMe = freeMe->next;
free(freeMe);
freeMe = holdMe;
}
}
int main()
{
char input[16];
NewNumber *start = NULL;
NewNumber *newest = NULL;
int res;
// infinite loop
while (1) {
// give advise
printf("Please enter a number or\n");
printf("'quit' to stop or 'print' to print/calculate\n");
// get input from user
res = scanf("%s", input);
if (res != 1) {
if (res == EOF) {
fprintf(stderr, "Got EOF, bailing out\n");
break;
} else {
fprintf(stderr, "something bad happend, bailing out\n");
break;
}
}
// check if a command was given
if (strncmp(input, "print", 5) == 0) {
PrintList(start);
continue;
} else if (strncmp(input, "quit", 4) == 0) {
printf("\n\nQuitting....\n");
break;
}
// otherwise gather numbers
if (newest == NULL) {
start = AddNumber(NULL, input);
if (start == NULL) {
fprintf(stderr, "AddNumber returned NULL\n");
break;
}
newest = start;
} else {
newest = AddNumber(newest, input);
if (newest == NULL) {
fprintf(stderr, "AddNumber returned NULL\n");
break;
}
}
}
CleanUp(start);
return 0;
}
You should really make a habit of checking all returns and if you don't: be able to give a good reason why you didn't.
Don't forget to switch on all warnings your compiler offers. Even if you don't understand them now, Google might have an answer and if not some people here do (in that order, thank you).
hello I am currently doing an assignment that is supposed to read in a file, use the information, and then print out another file. all using doubly linked list. Currently i am trying to just read in the file into a doubly linked list, print it out onto the screen and a file, and finally delete the list and close the program. The program works fine as long as I don't call the dlist_distroy function which is supposed to delete the string. as soon as I do it the program starts running and then a window pops up saying
"Windows has triggered a breakpoint in tempfilter.exe.
This may be due to a corruption of the heap, which indicates a bug in tempfilter.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while tempfilter.exe has focus.
The output window may have more diagnostic information."
I have revised the destroy and remove functions and cant understand the problem. my program is the following
main.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "dlinklist.h"
#include "DlistElmt.h"
#include "Dlist.h"
#include "dlistdata.h"
/****************************************************************************/
int main (int argc, char *argv[])
{
FILE *ifp, *ofp;
int hour, min;
Dlist *list;
DlistElmt *current = NULL, *current2 = NULL;
float temp;
list = (Dlist *)malloc(sizeof(list));
element = (DlistElmt *)malloc(sizeof(element));
if (argc != 3) { /* argc should be 3 for correct execution */
/* We print argv[0] assuming it is the program name */
/* TODO: This is wrong, it should be: usage: %s inputfile outputfile */
printf( "usage: %s filename", argv[0] );
} else {
// We assume argv[1] is a filename to open
ifp = fopen(argv[1], "r");
if (ifp == 0) {
printf("Could not open file\n");
} else {
ofp = fopen(argv[2], "w");
dlist_init(list);//, (destroy)(hour, min, temp));
while (fscanf(ifp, "%d:%d %f ", &hour, &min, &temp) == 3) {
current=list->tail;
if (dlist_size(list) == 0) {
dlist_ins_prev(list, current, hour, min, temp);
} else {
dlist_ins_next(list, current, hour, min, temp);
}
}
current = list->head;
while (current != NULL) {
if (current==list->head) {
current=current->next;
} else
if ((current->temp > (current->prev->temp +5)) ||
(current->temp < (current->prev->temp -5))) {
current2 = current->next
dlist_remove(list, current);
current = current2;
} else
current=current->next;
}
current = list->head;
while(current != NULL) {
printf("%d:%d %2.1lf\n",
current->time,
current->time2,
current->temp
);
fprintf(ofp, "%d:%d %2.1lf\n",
current->time,
current->time2,
current->temp
);
current = current->next;
}
//dlist_destroy(list);
//}
fclose(ifp);
fclose(ofp);
}
}
getchar();
}
dlistdata.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "dlinklist.h"
#include "DlistElmt.h"
#include "dlistdata.h"
/****************************************************************************/
void dlist_init(Dlist *list)
{
list->size = 0;
list->head = NULL;
list->tail = NULL;
return;
}
void dlist_destroy(Dlist *list) {
while (dlist_size(list) > 0) {
dlist_remove(list, list->head);
}
memset(list, 0, sizeof(Dlist));
return;
}
int dlist_ins_next(Dlist *list, DlistElmt *element, const int time,
const int time2, const float temp)
{
DlistElmt *new_element;
if (element == NULL && dlist_size(list) != 0)
return -1;
if ((new_element = (DlistElmt *)malloc(sizeof(new_element))) == NULL)
return -1;
new_element->time = (int)time;
new_element->time2 = (int)time2;
new_element->temp = (float)temp;
if (dlist_size(list) == 0) {
list->head = new_element;
list->head->prev = NULL;
list->head->next = NULL;
list->tail = new_element;
} else {
new_element->next = element->next;
new_element->prev = element;
if (element->next == NULL)
list->tail = new_element;
else
element->next->prev = new_element;
element->next = new_element;
}
list->size++;
return 0;
}
int dlist_ins_prev(Dlist *list, DlistElmt *element, const int time,
const int time2, const float temp)
{
DlistElmt *new_element;
if (element == NULL && dlist_size(list) != 0)
return -1;
if ((new_element = (DlistElmt *)malloc(sizeof(new_element))) == NULL)
return -1;
new_element->time = (int)time;
new_element->time2 = (int)time2;
new_element->temp = (float)temp;
if (dlist_size(list) == 0){
list->head = new_element;
list->head->prev = NULL;
list->head->next = NULL;
list->tail = new_element;
} else {
new_element->next = element;
new_element->prev = element->prev;
if (element->prev == NULL)
list->head = new_element;
else
element->prev->next = new_element;
element->prev = new_element;
}
list->size++;
return 0;
}
int dlist_remove(Dlist *list, DlistElmt *element)
{ /*, int time, int time2, float temp){ */
if (element == NULL || dlist_size(list) == 0)
return -1;
if (element == list->head) {
list->head = element->next;
if (list->head == NULL)
list->tail = NULL;
else
element->next->prev = NULL;
} else {
element->prev->next = element->next;
if (element->next == NULL)
list->tail = element->prev;
else
element->next->prev = element->prev;
}
free(element);
list->size--;
return 0;
}
This line is bad news:
if (element->next = NULL) (Close to bottom of dlistdata.c)
You assign the NULL to element->next instead of checking if it is NULL.
== vs =.
Since this is an assignment, my answer is to point you in the right direction, but I won't completely spell it out.
What do you think happens here?
dlist_remove(list, current);
current = current->next;