Reputation: 27
So I have a struct in another header file
struct MyStackStruct{
void **stk;
void *el;
int sizeStk;
int top;
int choice;
};
typedef struct MyStackStruct MyStack;
I call it s in main.
It's fine if I do something like s->top = -1;
on another file.c and I can print it out simply by printf("%d", s->top)
But I can't find a solution on how to print out the same thing in main. Nothing I tried works. Help!
Edit1: To make it clear. In struct.h I have
struct MyStackStruct{
void **stk;
void *el;
int sizeStk;
int top;
int choice;
};
typedef struct MyStackStruct MyStack;
then in main.c I define it as MyStack* s;
and send it to another file with functions using
MyStack *sP = &s;
and then something like push(sP);
if in push or any other function I do something like s->top = -1;
and printf("%d", s->top)
it prints out -1. If i do the same printf in main.c it prints out random numbers.
Upvotes: 1
Views: 1112
Reputation: 13786
You can put the struct definition in a header file struct.h
, and include it in main.c
with #include "struct.h"
. This way the compiler will have the details of the struct when compiling main.c
.
MyStack* s;
defines s
as a pointer to MyStack
, so &s
is if type pointer to pointer of MyStack
, which is MyStack**
. In that case you should just use s
for the operation, like push(s)
.
Also, you need to initialize the pointer before use it, you can use malloc
:
s = malloc(sizeof(*s));
Upvotes: 1