0

How can I make a pointer to a member of a struct, thats an array of ints. This is how the struct looks like:

typedef struct {
    volatile int x[COORD_MAX];
    volatile int y[COORD_MAX];
    volatile int z[COORD_MAX];
    //... other variables
} coords;

coords abc;

abc is a global variable. Now, I would like to get pointers to x,y and z arrays and save them to another array. Then acces them through passing a wanted index. Here is what I mean:

void test(int index1, int index2) 
{
    static volatile const int* coords_ptr[3] = {abc.x, abc.y, abc.z};
    coords_ptr[index1][index2] = 100;
}

So index1 would select which type of coordinates to choose from (x,y,z). And index2 would select which index of the coordinates to change.

Please note, that this is just a simplification of the code I am working on. But the principle is the same.

Thanks in advance!

EDIT:

I've written wrong code. Sorry for the confusion, this should be right now.

6
  • Sorry for the confusion, I mean in C. Commented Nov 28, 2014 at 17:30
  • 1
    In test, what coords object is the function operating on? coords is a type, not an object. Commented Nov 28, 2014 at 17:31
  • @nneonneo The compiler wasnt happy, because x,y and z are volatile so I needed to add it there to. Is it wrong? Commented Nov 28, 2014 at 17:31
  • ...are you still getting compiler errors? If so, you should post these errors. Commented Nov 28, 2014 at 17:32
  • 1
    coords_ptr[index1][index2] = 100; : coords_ptr[index1][index2] is const ! Commented Nov 28, 2014 at 17:40

2 Answers 2

1

There's only one small mistake: you made the pointers point to const volatile int, which prevents you from writing to them.

Just write

static volatile int* coords_ptr[3] = {abc.x, abc.y, abc.z};

and it'll work.

Sign up to request clarification or add additional context in comments.

Comments

1
#include <stdio.h>

#define COORD_MAX 3

typedef struct {
  volatile int x[COORD_MAX];
  volatile int y[COORD_MAX];
  volatile int z[COORD_MAX];
} coords;

coords abc;

void test(int index1, int index2)
{
  static volatile int* coords_ptr[3] = {abc.x, abc.y, abc.z};
  coords_ptr[index1][index2] = 100;
}

int main()
{
  test(0, 0);
  test(1, 1);
  printf("%i %i\n", abc.x[0], abc.y[1]);
  return 0;
}

output:

100 100

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.