Reputation: 1432
I am trawled these forums a looking for a solution to the problem but i could not seem to located one for my specific solution.
The problem i am having is, i want to implement a linked list aspect but i am not concerned about the head of the list, i just need to know the order to the structures.
The general idea is that:
struct 1 -> struct 2-> struct n->struct n+1
so i can then go:
struct n -> struct n-1 ........
i have defined my header as so:
typedef struct {
unsigned int value;
struct item* prev;
} item;
I read in muliple item values from a simple file which is basically:
23
421
12
234
etc ...
I load the items into an area of malloc'd memory large enough and when i read them in from the file i do this:
item* items;
items = malloc(no_of_lines * sizeof(item));
for (i = 0; i < no_of_lines; i++) {
if (fscanf(fp, "%d", &item[i] != EOF) {
}
}
But when i try to assign the previous to an item:
for (i = 0; i < no_of_lines; i++){
if(i != 0){
item[i].prev = item[i-1];
}
}
I get this error:
incompatible types when assigning to type ‘struct item *’ from type ‘item’
I have tried this:
for (i = 0; i < no_of_lines; i++){
if(i != 0){
item[i].prev = &item[i-1];
}
}
and
for (i = 0; i < no_of_lines; i++){
if(i != 0){
item[i].prev = (item *)&item[i-1];
}
}
both produce the warning:
assignment from incompatible pointer type
Any ideas?
Upvotes: 1
Views: 1080
Reputation: 98486
The problem is in this definition:
typedef struct {
unsigned int value;
struct item* prev; /* <---- here */
} item;
That line is not declaring a pointer to this struct, because the name item
is not introduced until the end of the full declaration. This is actually a nameless struct, with an alias named item
. Somewhere you have another, maybe similar, struct that is named item
:
struct item {
//unknown contents (for me)
};
The difference is that this type is named struct item
while the original one is just item
, without the struct
keyword.
If they are not the same, you should name them differently, to avoid confusion. And if they are actually the same, you should remove one of the declarations. Note that you can declare the named struct and an alias at the same time, and then they both will refer to the same type:
typedef struct item {
unsigned int value;
struct item* prev;
} item;
Or you can do it in separated declarations, it's just the same;
struct item {
unsigned int value;
struct item* prev;
};
typedef struct item item;
Other than that, the assignment is with the &
operator:
items[i].prev = &items[i-1];
Upvotes: 6
Reputation: 3381
Your problem maybe be the typedef. Just remove the keyword.
typedef struct {
unsigned int value;
struct item* prev;
} item;
This means declare a type called 'item'.
As a general rule: give everything a unique name. You have a 'struct item' and typedef 'item' and 'item = malloc'. Confusing.
Upvotes: 0