0

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.

user287474
  • 325
  • 1
  • 5
  • 19
  • You never change the address of an object in C during its entire life-time. The address is an object's identity. – 5gon12eder Mar 04 '16 at 17:04

2 Answers2

3

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;
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
dbush
  • 205,898
  • 23
  • 218
  • 273
1

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);
frogatto
  • 28,539
  • 11
  • 83
  • 129