user3453339
user3453339

Reputation: 77

Accessing malloc'd function in another file

How to access a malloc'ed element in an function that is present in another file

file1.c

#include<xyz.h> //all header files

extern struct SomeDefaultStructurefromHeader *str;

void myfunction(){
    str = (struct SomeDefaultStructurefromHeader*)malloc(sizeof(struct SomeDefaultStructurefromHeader));
    str->element1 = 1;
    str->element2 = 2;
}

How to I access the str values in another file say file2.c. My Idea was to to create a new element of SomeDefaultStructurefromHeader and then pointing str somehow to it. Would the use of extern help here if declared str as extern and then calling it in file 2

For eg: file2.c

struct SomeDefaultStructurefromHeader *st1;
void func2(){
    st1 = (struct SomeDefaultStructurefromHeader*)malloc(sizeof(struct SomeDefaultStructurefromHeader));
    st1 = str;
    printf(st1->element1) // this might return the value str->element1 which is 1
} 

How do I achieve this?

Thank you

Upvotes: 0

Views: 367

Answers (2)

Laura Maftei
Laura Maftei

Reputation: 1863

You should declare it in file1.c like this:

struct SomeDefaultStructurefromHeader *str;

and in file2.c add the extern specifier:

extern struct SomeDefaultStructurefromHeader *str;

Upvotes: 3

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

You need to declare in file2.c as well as:

extern struct SomeDefaultStructurefromHeader *str;

However, in one of the C file you must define global variable as:

struct SomeDefaultStructurefromHeader *str;

Upvotes: 2

Related Questions