r/C_Programming • u/gumnos • Jul 06 '26
Question anonymously initializing static pointers in self-referential data-structures?
I have a recursive data-structure (a simple linked list for purposes of this example) and wanted to statically define a linked-list. The following works fine:
#include <stdio.h>
typedef struct mytype_tag {
struct mytype_tag* next;
char* data;
} mytype;
mytype a = {
.next = NULL,
.data = "a",
};
mytype b = {
.next = &a,
.data = "b",
};
int
main() {
mytype* s = &b;
int i = 0;
while (s) {
printf("%d: %s\n", i++, s->data);
s = s->next;
};
}However, I have to explicitly define/declare a and then have b take &a.
Is there a way to do this with anonymous/unnamed intermediary structures, thinking an imaginary syntax something like
mytype b = {
.next = &((mytype)={
.next = NULL,
.data = "a",
}),
.data = "b",
};so I can build up the linked-list without naming each intermediary instance?
16
Upvotes
25
u/thegreatunclean Jul 06 '26
You are allowed to take the address of compound literals, so this is 100% kosher:
e: This is not safe in C++. Just in case anyone sees this and thinks they can copy/paste anything from C and be fine.
7
u/TheOtherBorgCube Jul 06 '26
Does this work for you?
3
u/sciencekm Jul 06 '26
You can create an array.
In the following example, I created a circular list and printed them.
#include <stdio.h>
typedef struct snode { struct snode *nxt; char *s; } node_t;
node_t nodes[3] = {
{ nodes + 1, "1st" },
{ nodes + 2, "2nd" },
{ nodes + 0, "3rd" } };
int main(void) {
node_t *start = nodes, *p = start;
do printf ("%s\n", p->s); while((p = p->nxt) != start);
return 0;
}
1
u/Thesk790 Jul 06 '26
Yes, you can but only using the heap memory (using malloc/free), not with the stack memory. I don't know if there is a way to do it without the heap, because you need a pointer that can lives more than just a function call, it needs to live in the heap where if you allocate, you free it
1
u/Thick_Clerk6449 Jul 06 '26
Isnt it meaningless? If you know the length of a linked list at compile time, why not just use an array?