0
struct example{
    int a;
    int b;
};

in main.c

I can write to this struct in main.c as follows

struct example obj;
obj.a=12;
obj.b=13;

Is there a way that I can directly write to the global memory location of this struct, so that the values can be accessed anywhere across the program?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
c_prog_90
  • 951
  • 20
  • 43

3 Answers3

0

Two ways:

You can take it address and pass it as a parameters to the functions that needs to access this data

&obj

Or, use a global:

Outside of any function, write struct example obj;

And in a header declare:

struct example {
  int a;
  int b;
};
extern struct example obj;

Edit: Reading this issue might be a good idea: How do I use extern to share variables between source files?

Community
  • 1
  • 1
Antzi
  • 12,831
  • 7
  • 48
  • 74
  • why does it need to be extern? – c_prog_90 Aug 07 '14 at 01:07
  • @thinkcool extern is used to make it publicly available to other files than main.c See: http://stackoverflow.com/questions/1433204/how-do-i-share-a-variable-between-source-files-in-c-with-extern-but-how – Antzi Aug 07 '14 at 01:13
  • `extern` means treat this as a declaration allowing other source files to use the name, but the instance is created with the `struct example obj;` at global scope in a single source file. – Keith Aug 07 '14 at 01:14
0

There are two ways to accomplish this:

1.

Create a header file that contains the following statement:

/* header.h */

extern struct example obj;

Add the following definition to one and only one source file:

/* source.c */

struct example obj;

Any source file that needs direct access to obj should include this header file.

/* otherFile.c */

#include "header.h"

void fun(void)
{
    obj.a = 12;
    obj.b = 13;
}

2.

Create getter/setter functions:

/* source.c */
static struct example obj;

void set(const struct example * const pExample)
{
    if(pExample)
        memcpy(&obj, pExample, sizeof(obj));
}

void get(struct example * const pExample)
{
    if(pExample)
        memcpy(pExample, &obj, sizeof(obj));
}

/* otherFile.c */

void fun(void)
{
    struct example temp = {.a = 12, .b = 13};

    set(&temp);
    get(&temp);
}

With this method, obj can be defined as static.

Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
-3

You can initialize it with a brace initializer, as in:

struct example obj = {12,13};

You could also declare a pointer to it, as in:

struct example* myPtr = &obj;
int new_variable = myPtr->a;

and then use that pointer to access the data members. I hope this addresses your question.

Logicrat
  • 4,438
  • 16
  • 22