(C) Understanding pointers and data structures, need help!
When should I declare struct instances as pointers and when shouldn't i?
What is the difference between structs and pointer to structs?
Question son generic structures and void pointers
In addition to the void* method, there's this trick I'd describe as "slightly abusive". Basically you have a "base struct" that just has a next in it. And then you include that struct in your data struct as the first field. Then you can cast your data struct to the base struct to get to the next.
(AFAIK, there's no UB or IB here, but someone please let me know if I'm mistaken.)
#include <stdio.h>More on reddit.com
#include <stdlib.h>
// Generic linked list stuff up here
struct node {
struct node *next;
};
struct llist {
struct node *head;
};
void llist_for_each(struct llist *l, void (*f)(void *))
{
for (struct node *p = l->head; p != NULL; p = p->next)
f(p);
}
void llist_init(struct llist *l)
{
l->head = NULL;
}
// In this function, n must point to a struct node or a struct that has
// struct node as the first member:
void llist_insert(struct llist *l, void *n)
{
struct node *new_node = n;
struct node *old_head;
old_head = l->head;
new_node->next = old_head;
l->head = new_node;
}
// Custom stuff below here
struct custom_node {
struct node llist_data; // Must be first!
int a;
char b;
float c;
};
struct custom_node *new_custom_node(int a, char b, float c)
{
struct custom_node *n = malloc(sizeof *n);
n->a = a;
n->b = b;
n->c = c;
return n;
}
void print_custom_node(void *node)
{
struct custom_node *n = node;
printf("%d %c %f\n", n->a, n->b, n->c);
}
int main(void)
{
struct llist l;
llist_init(&l);
llist_insert(&l, new_custom_node(1, 'a', 1.1));
llist_insert(&l, new_custom_node(2, 'b', 2.2));
llist_insert(&l, new_custom_node(3, 'c', 3.3));
llist_for_each(&l, print_custom_node);
}
// Output:
//
// 3 c 3.300000
// 2 b 2.200000
// 1 a 1.100000
I am a newbie to C. I recently learned about pointers and am comfortable with int pointers. However, I am having a hard time with structures.For instance, if I give a pointer to a structure how does the pointer point to all the data stored in the struct? How would that even be possible?Let me give an example -
int digit = 5 int *ptr = &digit; // Let's assume &digit is 1001 // Therefore ptr is now 1001
However, a structure is a contigous block of memory. What would a pointer to it store?