I think that I am having some issues with how linked lists work, please bear in mind that I am not an expert with C and that I have not worked with linked lists before.
I'm trying to take a text file with a list of things and store it in a linked list. I have 开发者_高级运维the following code right now:
typedef struct linked_list {
struct linked_list *next_ptr;
char name;
float price1;
float price2;
}linked_list;
struct linked_list *first_ptr;
char name_temp;
int writeList(void) {
// read input files
FILE *sh_list;
sh_list=fopen("case1/shoppingList.dat", "rw");
if (sh_list == NULL) {
perror("Cannot open file, you seem to have something mixed up...");
exit(8);
}
struct linked_list *current_ptr;
current_ptr = first_ptr;
while ((fscanf(sh_list, "%s", &name_temp)) !=EOF) {
next_ptr = malloc(sizeof(linked_list));
strcpy(name, name_temp);
//move to next node and complete the same task
}
};
I stopped at the //move... because I am struggling to get the code correct - my IDE is giving me errors. Similarly, I can't get it to read the variable "name" which I need to do in order to copy the string to the node.
You are getting next_ptr as undeclared because you have not delcared it.
Your code should look something like this ...
linked_list *next_ptr;
char name_temp[MAX_SIZE];
while ((fscanf(sh_list, "%s", &name_temp)) !=EOF) {
next_ptr = malloc(sizeof(linked_list));
strcpy(next_ptr->name, name_temp);
next_ptr->next_ptr = first_ptr;
first_ptr = next_ptr;
}
You should also make the declaration of name in linked list to be:
char name[MAX_SIZE];
In your fscanf
statement you specify that you're inputting a string, %s
, but name_temp
has type char
. You're going to have to change it to a char
array, like so:
char name_temp[100];
You'll have to make the array sufficiently big for your purposes. You'll also have to change the type of name
:
char name[100];
The error you are getting is because name
and next_ptr
are part of the struct linked_list
but you you have to create an instantiation of linked_list
to access name
. In your case, you have the current_ptr
so you should change it to:
current_ptr->next_ptr = malloc(sizeof(linked_list));
strcpy(current_ptr->name, name_tmp);
it should be strcpy(current_ptr->name, name_temp);
You are trying to refer to the name variable in the structure, which needs to be accessed through the current_ptr.
so similarly it should be current_ptr->next_ptr = malloc(sizeof(linked_list));
To access variable in a structure, you need to use the .
operator. When you are using a pointer to a structure, then you access its variables using the ->
operator.
精彩评论