Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address of an array declared inside a new struct

Tags:

c++

c

compilation

inside a definition like this

typedef struct 
{
    myType array[N];
} myStruct;

myStruct obj;

can I always assume that ([edit] assuming proper casting will happen which is not the focus of the question here [/edit])

(&obj == &obj.array[0])

will return TRUE or the should I worry about the compiler introducing extra padding to accomodate the myType alignment requisites? In theory this shouldn't happen as the struct has a single field but I'm not entirely sure about this.

like image 962
ad3angel1s Avatar asked May 03 '16 13:05

ad3angel1s


People also ask

How to access the adress of an element in an array?

*/ The same way you can pass a pointer to rules [i] to your function. A pointer to structure points to a structure, so the adress of an element still available. Yes. You access it as you would normally do with any other array, just grab it from the structure using the -> operator:

How do you access an array in a structure?

To access any structure object, you need to combine array indexed and structure member accessing technique. You can use either dot . or arrow -> (for pointers) operator to access structure array. The above code assigns data to first array object.

How many student marks are stored in structure array?

After structure declaration it declares an array of student structure, capable of storing 100 student marks. How to initialize structure array? Structure array initialization follows same syntax as you initialize single structure object.

What is the size of the array in a struct?

In other words, it's the pointer that's really in the struct, and not the actual array, thus, the size of the array doesn't matter. 4 items or 400 items, the amount of memory residing in the struct is still 32 bits on a 32 bit system. Also, string [] is a type, while string [4] is technically not a type.


1 Answers

With a proper cast, this will always return true.

From section 6.7.2.1 of the C standard:

13. Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. 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.

like image 59
dbush Avatar answered Oct 05 '22 16:10

dbush