I have a variable in a C file called list.c and I initialize the var with the function initList(void) inside my main.c. How can I get the variable while being inside my main.c?
main.c:
#include <stdlib.h>
#include "list.h"
int main() {
initList();
return 0;
}
list.c:
#include "list.h"
listItem *firstItem;
listItem *currentItem;
void initList(void) {
currentItem = calloc(1, sizeof(listItem));
currentItem->data = 0;
currentItem->lastItem = NULL;
currentItem->nextItem = NULL;
firstItem = currentItem;
}
void listInsert(int data) {
listItem *newItem = calloc(1, sizeof(listItem));
newItem->data = data;
newItem->lastItem = currentItem;
newItem->nextItem = NULL;
currentItem = newItem;
}
list.h:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
void initList(void);
void listInsert(int data);
typedef struct listItem {
void *lastItem;
void *nextItem;
int data;
} listItem;
#endif
As you can see I initialize the variable in my initList(void) function which I call in the main.c file. Now I want to do something with my variable. For example I would like to insert something into the list with my function listInsert(int data) which does not work.
Does C not keep the reference to both my variables firstItem, currentItem?