'Pointers being declared in structs in c
struct charact
{
char ch;
int occurs;
struct charact *next;
};
What is "next" in this struct exactly?
Solution 1:[1]
What is "next" in this struct exactly?
next is a struct charact pointer. It can be used to point at instances of struct charact or NULL to indicate that it's not pointing at a struct charact.
This particular struct looks like it is a node in a forward linked list. That is, a linked list that only has references to the next element in the list.
A (double) linked list would also have a struct charact pointer to be able to point at the previous element in the list:
struct charact
{
char ch;
int occurs;
struct charact *prev;
struct charact *next;
};
For such a node, linking them together could look like this:
struct charact a = {.ch = 'a'};
struct charact b = {.ch = 'b'};
struct charact c = {.ch = 'c'};
a.next = &b;
b.prev = &a;
b.next = &c;
c.prev = &b;
struct charact *head = &a;
struct charact *tail = &c;
Here head would point at a. a.next points at b and b.next points at c - and you would have the ability to go backwards in such a list too via the prev member:
// backwards:
for(struct charact *curr = tail; curr != NULL; curr = curr->prev) {
printf("%c\n", curr->ch);
}
// forward:
for(struct charact *curr = head; curr != NULL; curr = curr->next) {
printf("%c\n", curr->ch);
}
Note: The actual instances of list nodes are usually not created as automatic variables like above but created and destroyed dynamically using malloc/free.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
