I'm trying to make a program that read a file line by line and then put the readed line into a a linked list, my problem is to add the string 开发者_如何学Pythonto list. Look at the code, in the else test you can see my problem.
#include<stdlib.h>
#include<stdio.h>
struct list_el {
char *ord;
struct list_el * next;
};
typedef struct list_el item;
int main(int argc, char *argv[]) {
int c;
item *curr, *head;
head = NULL;
FILE *fileHandle = fopen("tresmaa.txt", "r");
while((c = fgetc(fileHandle)) != '\n' || c != EOF)
if(c == EOF) {
printf("\n");
break;
} else {
curr = (item*)malloc(sizeof(item));
curr->ord = "I cant point curr -< ord = c, how can i point the readed sentences to the value Ord?";
curr->next = head;
head = curr;
putchar(c);
}
curr = head;
while(curr) {
printf("%s\n", curr->ord);
curr = curr->next ;
}
}
curr->ord = "some string" is wrong
instead you need to allocate a buffer and place the string in it
e.g.
curr->ord = malloc( strlen(yourstring) + 1 );
strcpy(curr->ord, yourstring);
because
curr = (item*)malloc(sizeof(item));
only allocates the struct including the 'ord' pointer, but not what it points to.
another thing that looks a bit suspicious is
curr->next = head;
head = curr;
looks more like the name should have been 'prev' and not 'next' the way you do it (LIFO)
otherwise if you want a "normal" FIFO linked list just have a head ptr and an end ptr, then use the end ptr to append elements while keeping the head pointing to the first list element.
I see your problem in the else. :)
Your malloc of the struct is not sufficient. This malloc only creates the memory of the struct memory (two pointers) not the memory inside. You'll have to malloc your char memory (ord
) with the proper size of the string as well. Use strlen
and add one for null to determine size of this string.
curr->ord = "some string"
is right!
精彩评论