Skip to main content

Walkthrough with Structs

When doing a walkthrough with structs, The tables that you create should include sub - columns for each data member.

Consider the following walkthrough:

#include <stdio.h>
struct Demo
{
int apple;
int banana;
int orange;
char grapes[6];

};
int main(void)
{
struct Demo first = {2,4, 2, "lgwrd"};
char temp;
int i;
printf("%s\n", first.grapes);
temp = first.grapes[first.apple];
first.grapes[first.apple] = first.grapes[first.banana];
first.grapes[first.banana] = temp;
printf("%s\n", first.grapes);
for(i = 0; first.grapes[i]!='\0';i++){
first.grapes[i]+=first.orange;
}
printf("%s\n", first.grapes);
return 0;
}

walkthrough table at first printf

Our first line of output is therefore this:

lgwrd

Looking now at this line:

	temp = first.grapes[first.apple];

the first.apple is 2. Thus the above becomes:

	temp = first.grapes[2];

This is the letter w.

Thus our table becomescomes:

table after temp = first.grapes[first.apple]

Similarly:

first.banana = 4

Thus, the next 2 lines becomes:

	first.grapes[2] = first.grapes[4];
first.grapes[4] = temp;

After we execute these two lines of code, end up with the following:

table after first.grapes[4]=temp;

We then print first.grapes:

lgwrd
lgdrw

We then go through the loop this is the table as we update for each iteration of the loop:

we end up with storing the word "nifty" into the grape data member.

Thus our output is:

lgwrd
lgdrw
nifty