T
T
Test2019-03-02 19:17:52
C++ / C#
Test, 2019-03-02 19:17:52

How to bind struct field values ​​to a pointer?

struct Vector {
    void *x;
    void *y;
};

struct Complex {
    int real;
    int imagine;
};

int main(){
  struct Vector v;
//to do

return 0;
}

I want to bind x and y to Complex so I can do something like this:
v.x.real =5;
v.x.imagine = 7;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2019-03-02
@YyyzzxxxI

Exactly the way you want won't work, a null pointer can't have a field. We'll first have to cast it to a pointer to a structure that has the field real. And since it's a pointer, you need to use the arrow operator to access the field.

struct Vector {
  void *x;
  void *y;
};

struct Complex {
  int real;
  int imagine;
};

int main() {
  struct Vector v;
  struct Complex c1;

  v.x = &c1;

  ((struct Complex*) v.x)->real = 42;

  return 0;
}

D
Denis Zagaevsky, 2019-03-02
@zagayevskiy

void * is a pointer to who knows what.

struct Vector {
   struct Complex x;
   struct Complex y;
}

I think that's how it should be.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question