0

I have two structures as follows

typedef struct Rsp_s {
    u8    code;
    u8 Count;
}Rsp_t;

typedef struct Field_s {
     u8    State;
     u8    present;
     u8    previous;
     u8    event;
} Field_t

Then i have

Rsp_t *rsp;
Field_t data[3][7]

I want data[0][0] to follow rsp->Count. How do i do that?

data = (Field_t *)(&(rsp->Count) +1);

does not do it.

4
  • 1
    you've swapped the order, kind of. You'd also need to declare a as a pointer to an int pointer Commented Jul 9, 2014 at 17:00
  • &b[0][0] = a attempts to set the value of &b[0][0] to the value of a. But &b[0][0] cannot be modified since it's fixed. Thus the error you see. Commented Jul 9, 2014 at 17:01
  • actually I'm wrong, a = &b[0][0]; is legal it seems, but you'd certainly won't be able to dereference it with [][] Commented Jul 9, 2014 at 17:04
  • 1
    @Ben Sure you can; you just need some casting, like this: ((int**)a)[0][0] = 1; Not that it would likely be a useful thing to do, but this is C, you're allowed to shoot yourself in the foot. Commented Jul 9, 2014 at 17:17

2 Answers 2

2

When you declare a variable like this ...

int b[3][7];

... its memory location is assigned by the compiler if static or given memory from the stack if automatic, and therefore cannot be changed programatically. You can however access this memory, and read to and write from it, by using a pointer ...

int (*a)[7] = b;

The following are equivalent:

b[0][0] = b[1][1];
a[0][0] = a[1][1];
Sign up to request clarification or add additional context in comments.

4 Comments

I think you should also add that the following is legal and works: int* a = (int*)b[0]; gets you the 1-d pointer to the contiguous memory. I always use int* a = &b[0][0] cuz I like it better, but to each their own.
And to clarify, when he said the following are equivalent, another way to say it is &pb[x][y]==&b[x][y]
I've never seen this before: int (*pb)[7]. What exactly are you doing here?
@sherrellbc int (*a)[7] declares one variable, a pointer to a 2D array, [n][7] in size. int *a[7] would declare 7 variables, each a pointer to a single int or 1D int array, [n] in size.
0

Your assignment is the wrong way round. You want to assign to a the address of b[0][0], so:

a = &b[0][0];

2 Comments

@user3821434 I don't think you know what you want
@user3821434, what AntonH has done above is exactly that. Doing this does not replace the base of b by a, but rather points a to the base of b.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.