Let’s say I define a struct as
typedef struct worker{
char name[20];
int age;
} worker
and then I create an array of lenght 20 of such structures,
worker *business;
business = malloc(20 * sizeof(worker));
Is there any "natural" (i.e. already implemented in the language) way to obtain, from such array, the sub-array of the "age" element?
I’m thinking of something along the lines of
business.age
where business.age is the array of integers of the age of each element of business?
>Solution :
The age fields of structs in your array do not form a continuous area of memory. The layout in memory is similar to this:
business[0] business[1]
[ 20 bytes of name | 4 bytes of age ][ 20 bytes of name | 4 bytes of age][ 20...
Your ages are separated by the name arrays. Since Arrays in C have to be continuous areas of memory without gaps, it is not possible to just refer to an "array" of ages. You can, however, iterate over the ages easily with a for loop or write a function/define a macro to access the age at certain index:
int get_age_at_index(worker* arr, int idx) {
return arr[idx].age;
}
// OR
#define GET_AGE_AT_INDEX(arr, idx) (arr[idx].age)
This could potentially allow for similar semantics to accessing an element of array.
If you are ok with copying data, you may just allocate an array for 20 ints and copy age from each struct:
int ages[20] = { 0 };
for(int i; i < 20; i++) {
ages[i] = business[i].age;
}