Hi,
I'm having a bit of trouble with this linked list. It imports a ten-line text file, and the last lines of the code are supposed to print the 1st line of the text file, but instead it prints the last line of it. Been working on this a while and still can't figure it out.
I've trimmed down the code a bit, but these basics still illustrate the problem I've been having.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
define BLOQ
*/
typedef struct BLOQ {
char *lineptr; /* text of line */
struct BLOQ *link;
struct BLOQ *prevlink;
int nodeLength;
/* pointer to next line */
} BLOQ;
int main (void)
{
char inbuff[ 82 ];
char file_name[ 82 ];
char *tmpchr;
int numline;
FILE *fp;
BLOQ top;
BLOQ *temp = NULL;
BLOQ *bottom = NULL;
/*
assign mem block for tmpchr
*/
tmpchr = malloc(82);
/*
assign mem block for bottom
*/
bottom = malloc(40);
/*
assign value to bottom->lineptr
*/
bottom->lineptr = "[BOF]\n";
/*
assign value to top
*/
/*
get file
*/
printf( "\nEdit which file? " );
fgets( inbuff, 82, stdin );
sscanf( inbuff, "%s", file_name );
printf( "\n" );
fp = fopen( file_name, "r" );
temp = malloc(40);
bottom -> link = temp;
top = *bottom;
/*
move to next node
*/
bottom = bottom->link;
/*
fill nodes from file
*/
for(numline=1 ; fgets( tmpchr, 82, fp ) != NULL ; numline++)
{
bottom -> lineptr = tmpchr;
temp = malloc(40);
bottom -> link = temp;
bottom = bottom -> link;
}
temp = ⊤
printf("top lineptr is %s\n",top.lineptr);
printf("temp is %s\n",temp->lineptr);
/* move to next node */
temp = top.link;
/* should print first line of text file, but prints last instead,
which is also the value of tmpchr, but not sure why*/
printf("temp is %s\n",temp->lineptr);
return 1;
}