Reputation: 12864
Suppose I have array of chars:
char buffer[1024];
The array in fact contains chain of structures in sequence.
struct MyStruct {
char name[4];
int num1;
int num2;
}
I want to loop through the array:
MyStruct *p;
for(int i = 0;i < sizeof(buffer);i += sizeof(MyStruct))
{
// how can I point p to some place in buffer here?
}
I want to point p
to start of buffer
, the to buffer + 12
etc.
Upvotes: 1
Views: 59
Reputation: 495
One issue to consider is that the char buffer might not be properly aligned for a struct (and, in this case, its int members num1
and num2
). Depending on the platform and implementation, a 4-byte, 8-byte or 16-byte alignment might be required. For that reason, one alternative is to declare the buffer in terms of MyStruct
initially and then access it via a char pointer:
MyStruct buffer[1024 / sizeof(MyStruct)];
char * cp = (char *) buffer;
// fill the buffer via cp
for (size_t i = 0; i < sizeof(buffer); ++i)
{
// do stuff with buffer[i]
}
If that approach is not possible, the buffer needs to be copied to another buffer with safe alignment; For example:
size_t n = sizeof(buffer) / sizeof(MyStruct);
MyStruct * p = (MyStruct *) malloc(n * sizeof(MyStruct));
if (!p) { exit(EXIT_FAILURE); }
memcpy(p, buffer, n * sizeof(MyStruct)); // copy buffer to p
for (size_t i = 0; i < n; ++i)
{
// do stuff with p[i]
}
Upvotes: 3
Reputation: 25286
You let p
point to the first struct in the buffer, then increment it on each iteration:
MyStruct *p= (struct MyStruct *) buffer;
for(int i = 0; i < sizeof(buffer); i += sizeof(MyStruct), p++)
{
// your code
}
...and yes, this assumes the structs are contiguous in memory, with no padding in between.
Upvotes: 0
Reputation: 50180
first note that you are assuming that this will work. That there is no padding between the elements of the struct. Having said that do this:
MyStruct *s = (MyStruct*)(buffer + i)
Upvotes: 1