1

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.

2
  • 3
    You are about to cross a thin red line here called strict aliasing... Commented Sep 29, 2016 at 18:06
  • Such buffers are typically from marshalling/serialisation. Learn about that subject and do it the correct way member-wise. First define the format of the data in the buffer so that it does not rely on implementation-specific details. Commented Sep 29, 2016 at 18:14

3 Answers 3

3

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]
}
Sign up to request clarification or add additional context in comments.

Comments

1

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)

2 Comments

Thanks, that exactly what I need.
There is a bunch of other things one has to assume... Like the alignment. Not my DV, though, if you are wondering..
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.