I did a lot of linked lists already, but I didn't use them for a while and didn't really programm anything, therefore I am litterally lost. The following is my Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int age;
int pers_num;
char name[100];
void *previous;
void *next;
}Person;
int main(){
Person first_element;
Person last_element;
first_element.next = (Person *)(&last_element);
last_element.age = 19;
printf("%d\n",(&last_element)->age);
printf("%d\n",(first_element.next)->age);
}
Could you explain to me why following error is thrown?
speicher.c: In function 'main':
speicher.c:22:39: warning: dereferencing 'void *' pointer
23 | printf("%d\n",(first_element.next)->age);
| ^~
speicher.c:23:39: error: request for member 'age' in something not a structure or union
As I understand it "first_element.next" should be the pointer which points at last_element. therefore you should be able to use the -> to access the data inside last_element. The line 22 Runs perfectly even thought it should have the same Output as line 23, where the error is thrown.
You can't dereference a void pointer because it's a pointer that references a void type:-) In other words, it doesn't really know what actual type it points at. The reason why the two lines behave differently are, keeping in mind that a->b
is just syntactic sugar for (*a).b
:
printf("%d\n",(&last)->age);
// This (&last)->age, which is actually the same
// as last.age. In both cases, the type being used
// to get the age field is Person, so no problem.
printf("%d\n",(first.next)->age);
// This (first.next)->age is the same as
// (*(first.next)).age. Because first.next is of type
// void *, it cannot be dereferenced.
What you are doing is akin to declaring a variable with void x
, which is not valid (don't confuse that with void *x
which is valid).
You would be better off (within the structure) pointing to the actual type you want, with something like:
typedef struct s_Person { // A
int age;
int pers_num;
char name[100];
struct s_Person *previous, *next;
} Person; // B
Note that you cannot use the Person
type definition while you're creating it, since it does not yet exist. Simplistically, you can think of it coming into existence at the B
point. The named structure s_Person
comes into existence at A
so it can be used within the structure.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.