简体   繁体   中英

Assign values to a struct

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?

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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM