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?

val - disappointed in SE
  • 1,475
  • 3
  • 16
  • 40

2 Answers2

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]).

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

Correct way is

__s32 *pointer = x->array

It is equal to

__s32 *pointer = &(x->array[0])
val - disappointed in SE
  • 1,475
  • 3
  • 16
  • 40