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;
and then we use:
- Code: Select all
printf("var: %p\n", &var);
we are accessing the variable position in memory.
Then, if we use:
- Code: Select all
int *var = NULL;
We are supposing to use var to hold a memory position.
So, when we use:
- Code: Select all
printf("var: %p\n", (void *) &var);
(I had to type cast it to void * to match the specifier flag %p).
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);
Now, raising a bit the complexity, I always struggle when it comes to pass pointers to functions and I never get it right when it comes to passing pointers to pointers or pointers to arrays or pointers to structures into functions.
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;
}
I understand we are accessing only memory positions.
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;
}
And questions starts right here, because what I do now, will change the rest of the program.
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?