[Solved] Why does incrementing a pointer work, but treating it as an array fail? Part 2 [closed]


I’m not sure what your question is, but this code probably doesn’t do what you want:

printf("main Pointer to struct." EOL);
for (int i=0; i<count; i++)
{
    printf("index: %d  useless1: %d" EOL, i, b->useless1);
    printf("index: %d  useless2: %d" EOL, i, b->useless2);
    b++;
}
printf(EOL);

printf("main Index into array of structures." EOL);
for (int i=0; i<count; i++)
{
    printf("index: %d  useless1: %d" EOL, i, b[i].useless1);
    printf("index: %d  useless2: %d" EOL, i, b[i].useless2);
}
printf(EOL);

The first loop changes the value of b, so the second loop doesn’t start where you think it does.

Consider something like this:

type1* bOrig = b; // store the original value
printf("main Pointer to struct." EOL);
for (int i=0; i<count; i++)
{
    printf("index: %d  useless1: %d" EOL, i, b->useless1);
    printf("index: %d  useless2: %d" EOL, i, b->useless2);
    b++;
}
printf(EOL);
b = bOrig; // restore the original value

printf("main Index into array of structures." EOL);
for (int i=0; i<count; i++)
{
    printf("index: %d  useless1: %d" EOL, i, b[i].useless1);
    printf("index: %d  useless2: %d" EOL, i, b[i].useless2);
}
printf(EOL);

3

solved Why does incrementing a pointer work, but treating it as an array fail? Part 2 [closed]