0
votes

I have a program made of 3 files.

  • main.c contains the external variables for the stack and contains the code to parse input and pass the input to the functions in stack.c

  • stack.c //contains the functions to execute the operations on the stack push/pull etc

  • stack.h //contains the function prototypes

The program currently uses a global integer array as a stack.

Im now trying to convert the program to use a linked list for the stack instead of the integer array.

My issue is I don’t know where I should declare the struct and where I should declare the struct members. Should i put them in the main.c outside the main function, in the stack.h header file ?

my struct declaration

struct node {
   int value;
   struct node *next;
};

struct node *first = NULL;
struct node *new_node = NULL;


new_node = malloc(sizeof(struct node));
3
the struct definition and the declarations of the pointers can be kept global. new_node = malloc(sizeof(struct node)); must be inside a function (eg main()), since it generates "code", not "data". - wildplasser
I'm not sure why you need two pointers for a linked list stack. - Medinoc

3 Answers

1
votes

In stack.c

#include "stack.h"
struct node *first = NULL;
struct node *new_node = NULL;

In stack.h

struct node {
   int value;
   struct node *next;
};

extern struct node *first;
extern struct node *new_node;

In main.c

#include "stack.h"
//inside main
//new_node = malloc(sizeof(struct node)); //don't forgot to free it
0
votes

Excluding any debate on global variables, I see two options:

1) Define your structure only in stack.c, and just declare it in stack.h:

/*stack.h*/
struct node;

extern struct node *g_first_node = NULL;
extern struct node *g_new_node = NULL;

2) Put the structure definition in stack.h, so all the code referncing it can use it.

0
votes

Put your structure definition and extern variable declaration in header file and include your header file in other .c files. [don't forget to add header guards (include guard)].

Then, create variables of the structure type in your main.c [and use in stack.c file also]. That's the common analogy.

Example

//stack.h
struct node {
   int value;
   struct node *next;
};

extern struct node *g_first_node;
extern struct node *g_new_node;

then, in main.c

#include "stack.h"
struct node *g_first_node= NULL;
struct node *g_new_node= NULL;