You have two major problems.
First, you have a logical error in that you advance your pointer before printing out the value it points to; instead of printing the value of the thing you just set, you're printing the value of the next uninitialized member. You need to reverse the order of the advance and print statements like so:
printf("ptr value = %d\n", *ptr);
ptr++; // note no * operator
Or just combine the operation in one expression:
printf("ptr value = %d\n", *ptr++);
This assumes that you can use %d
to print a bool
value - I'm not sure about that offhand (may have to explicitly cast the argument to (int)
).
But you have a bigger problem - it's not guaranteed that you can iterate through the members of a struct
type with a pointer like this. Even though all the members are the same type, it's not guaranteed that there won't be padding between members (it depends on the size of the bool
type and the alignment requirements of your platform).
Your code may work as intended, or it may lead to corrupted data within your struct
instance, or any number of other issues. The safer thing to do is use a separate array of pointers to those members, since it is guaranteed that you can iterate through an array with a pointer:
bool *members[] = { &item.bOne, &item.bTwo, &item.bThree, &item.bFour, NULL };
bool *ptr = members[0];
while ( ptr )
{
*ptr++ = 1;
}
If you still want output, you'd write
*ptr = 1;
printf( "ptr value = %d\n", *ptr++ );
You could get creative and combine the assignment and pointer advance within the print statement:
printf( "ptr value = %d\n", (*ptr++ = 1) );
but that would probably get you hit.