0

I've got a struct x:

struct x {
    __s32 array[10];
};

How can I create a pointer to array x->array, if I've got only pointer to stucture?

6
  • 1
    To which array? Commented Jan 8, 2017 at 19:20
  • 1
    &(x->array) perhaps? Commented Jan 8, 2017 at 19:20
  • @HermannDöppes maybe it's the array member variable? Commented Jan 8, 2017 at 19:21
  • @SouravGhosh I believe Hermann's point is that a field declared in a structure, that has an array type, is not an array. A field in a particular instance of the structure is an array. Commented Jan 8, 2017 at 19:52
  • @immibis Quite right, agree. Commented Jan 8, 2017 at 19:54

2 Answers 2

2

The straightaway method is the commonly used way, as

 struct x * ptr = NULL;
 //allocation
 __s32 * otherPtr = ptr->array;  //array name decays to pointer to first member
 __s32 (*p) [10] = &(ptr->array); // pointer to whole array.

Otherwise, there's another way, but for specialized cases, quoting C11, chapter §6.7.2.1, Structure and union specifiers

[...] A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

So, in case, the array variable is the first member (or only member, as seen in above example) of the structure, the pointer to the structure variable, suitably converted to proper type, will also point to the beginning of the array member variable.

In this case, you can use a cast of (__s32 (*)[10]).

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

2 Comments

And that is better than &someInstanceOfX->array how?
@immibis emmm..OK, I did not realize that this was supposed to be a better way, I just thought of an alternate way.
1

Correct way is

__s32 *pointer = x->array

It is equal to

__s32 *pointer = &(x->array[0])

1 Comment

@SouravGhosh I suspect OP meant "pointer to first element of array"

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.