Reputation: 45
I'm trying to get more comfortable building and using linked lists in C, and for the most part I think I have the basics down. However, I am running into problems in regards to Scope, specifically the linkage of a Pointer to a Pointer of structs.
In my linked_list.c implementation I am using a main
function to test out and play around with the linked list functions I've built. But the eventual goal is to run Main from another file, and only reference the few functions I'd need externally from a header file.
The implementation I'm using right now DOES work, but it seems to rely on me declaring the struct list**
inside my (temporary)) main
function.
It's my understanding that if you declare a variable/pointer outside of a block, you can control the linkage to be internal, accessible to other functions in the file, using the static
command. What I would like to be able to do is call a function like void initialize_list()
from OUTSIDE the program and have it initialize this internally linked list**
.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
int value;
struct node *next;
};
struct list {
struct node *head;
struct node *tail;
int size; // Maintains current size of list
};
static struct list** work_list;
void dirty_init(void){
struct list* new_list = malloc(sizeof(struct list));
new_list->head = NULL;
new_list->tail = NULL;
new_list->size = 0;
*work_list = new_list;
}
Running my dirty_init
function returns a segfault.
The version of code that DOES work is quite similar, but it seems to rely on the **work_list
being declared inside of my main
function before passing it to initialize_list
.
void initialize_list(struct list **out_list){
struct list* my_list = malloc(sizeof(struct list));
my_list->head = NULL;
my_list->tail = NULL;
my_list->size = 0;
*out_list = my_list;
}
int main(void){
int i;
struct list **work_list;
initialize_list(work_list);
}
This is all well and good, but it has the drawback of making my **work_list
pointer internally linked to the Main block. Any ideas where I am going wrong trying to get the dirty_init
function to work?
Upvotes: 0
Views: 527
Reputation: 72657
This here:
int main(void){
int i;
struct list **work_list;
initialize_list(work_list);
}
can't work. C is pass by value and you pass an uninitialized value, which is then used as a result pointer. Did you mean
int main(void){
int i;
struct list *work_list;
initialize_list(&work_list);
}
instead?
Upvotes: 2