user287474
user287474

Reputation: 325

Change address of struct in C

Let's say that I was given a struct and I need to assign all of it's attributes to a particular address. The code below is giving me a conditional error, but i'm not trying to evaluate it.

struct header block_o_data;
block_o_data.a = 1;
block_o_data.b = 2;
void* startingAddress = sbrk(0);
&block_o_data = *address;

Please let me know what im doing wrong.

Upvotes: 0

Views: 6196

Answers (2)

frogatto
frogatto

Reputation: 29285

Suppose you have a struct like this:

struct mystruct {
    int a;
    char b;
};

then you probably need something like this:

// A pointer variable supposed to point to an instance of the struct
struct mystruct *pointer;

// This is a general address represented by void*
void *addr = some_function(0);

// Cast that general address to a pointer varibale pointing to
// an instance of the struct
pointer = (struct mystruct *) addr;

// Use it!
printf("%d", pointer->a);

Upvotes: 1

dbush
dbush

Reputation: 223937

In the assignment to block_o_data, you're taking its address and trying to assign a value to it. The address of a variable is not an lvalue, meaning the expression cannot appear on the left side of an assignment.

You need to declare a pointer to a struct, then assign it the address of where the values actually live:

struct header *block_o_data;
void* startingAddress = sbrk(0);
block_o_data = startingAddress;

Upvotes: 3

Related Questions