This is a subject that I always struggled with.
Simple pointers are ok.
I know that when we have, inside the same scope:
Code: Select all
int var = 5;
Code: Select all
printf("var: %p\n", &var);
Then, if we use:
Code: Select all
int *var = NULL;
So, when we use:
Code: Select all
printf("var: %p\n", (void *) &var);
we are also accessing the variable memory position too.
I get a 'nil' keyword if I try to access it the same way but without the '&'. Not sure what that stands for.
And if I want to access the actual value stored in that memory position, I use:
Code: Select all
printf("var: %d\n", *var);
So, for instance, if I have:
Code: Select all
typedef struct node{
...;
...;
}Node;
int main(void){
Node root = NULL;
Node *head = NULL;
printf("Test: %p\n", (void *) &root);
printf("Test: %p\n", (void *) &head);
return 0;
}
Now, what I want to do is to create a double linked list of structs and I don't want to use global variables at all.
I guess 99% of the search results either from youtube or google, uses global variables to build linked lists.
But I want to pass all variables via pointers, avoiding global variables. And the only global thing is the struct.
So this is how I start:
Code: Select all
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
...;
}Node;
int main(void){
Node *root = NULL;
return 0;
}
I have several options, or at least 2.
Create a variable to initialize the root struct or initialize it in the main() function. I can't decide which is better and more solid practice.
Then, depending on the way to go, I'll have to deal with how to pass the variables to functions and how and what to return.
So, to start, what would be the best and more solid practice?