K
Kelvin Moss
Hi group,
I have an array of structure.
Say -
typedef struct Person {
int i;
int j;
int k;
}person;
person p[10]={{25, 2, 7},
{7, 3, 89},
{45, 56, 78}};
I am interested in processing all the first members of the struct in
the array together, all the second members of the struct together and
so on... i.e. i need to get {25, 7, 45}, {2, 3, 56} together ans so
on...
I came at the following approach but it doesn't work. Could someone
please tell me the right way to do it.
Thanks.
#include <stdio.h>
#include <stdlib.h>
typedef struct Person {
int i;
int j;
int k;
}person;
person p[10]={{25, 2, 7},
{7, 3, 89},
{45, 56, 78}};
size_t foo(void)
{
return offsetof(person, j);
}
int main()
{
int *struct_addr = NULL;
int addr;
int i;
int count = 0;
size_t offset;
offset = foo();
addr = &(p[0]) + offset; /* This seems wrong */
/* Incorrect pointer arithmetic */
for (i = 0; i < 3; i++) {
count += *((int *) addr);
addr += sizeof(person); /* This too ?? */
}
printf("%d", count);
}
I have an array of structure.
Say -
typedef struct Person {
int i;
int j;
int k;
}person;
person p[10]={{25, 2, 7},
{7, 3, 89},
{45, 56, 78}};
I am interested in processing all the first members of the struct in
the array together, all the second members of the struct together and
so on... i.e. i need to get {25, 7, 45}, {2, 3, 56} together ans so
on...
I came at the following approach but it doesn't work. Could someone
please tell me the right way to do it.
Thanks.
#include <stdio.h>
#include <stdlib.h>
typedef struct Person {
int i;
int j;
int k;
}person;
person p[10]={{25, 2, 7},
{7, 3, 89},
{45, 56, 78}};
size_t foo(void)
{
return offsetof(person, j);
}
int main()
{
int *struct_addr = NULL;
int addr;
int i;
int count = 0;
size_t offset;
offset = foo();
addr = &(p[0]) + offset; /* This seems wrong */
/* Incorrect pointer arithmetic */
for (i = 0; i < 3; i++) {
count += *((int *) addr);
addr += sizeof(person); /* This too ?? */
}
printf("%d", count);
}