Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following variable definitions: char a, *b, *c; int d[2], *e; int i

ID: 3771060 • Letter: C

Question

Consider the following variable definitions:

char a, *b, *c;

int d[2], *e;

int i, *j;

How many total bytes does this code allocate for variables? Assume a 32-bit representation for integer and pointer values.

a sizeof(char)

b sizeof(char *)

c sizeof(char *)

d 2*sizeof(int)

e sizeof(int *)

i sizeof(int)

j sizeof(int *)

Total number of bytes for each?

What is the output of the following piece of code? (Use the above variable definitions).

j = &i;

*j = 50;                   /* i = 50 */

e = &d[0];

*e = 20;                   /* d[0] = 20 */

e[1] = 30;                 /* d[1] = 30 */

j = &d[1];                

*j = i+d[1];          /* d[1] = 80 */

printf(“d = [%d, %d]n”, d[0], d[1]);

char a, *b, *c;

int d[2], *e;

int i, *j;

Explanation / Answer

Bytes allocated to

a = 1 //since char always have 1 bytes allocated to them

b = 4 //pointer is always allocated 4 ( in 32 bit representation ) bytes irrespective of their data type

c = 4 //same as b

d = 8 //it contains 2 integers, 1 integer occupies 4 bytes hence total of 8 bytes

e = 4 // pointer always have 4 bytes for them

i = 4 //int has 4 bytes (32 representation)

j = 4 //because it is a pointer

Next question

j = &i;

*j = 50;                   /* i = 50 */

e = &d[0];

*e = 20;                   /* d[0] = 20 */

e[1] = 30;                 /* d[1] = 30 */

j = &d[1];                

*j = i+d[1];          /* d[1] = 80 */

printf(“d = [%d, %d] ”, d[0], d[1]);

output -> d = [20, 80]

explanation

j = &i means j is an alias of i i.e. i can also be written as j , i and j are practically same just the difference of spellings.

*j = 50 means 50 is stored in the memory location of j . Since I said j and i are practically same hence value of i has now become 50

e = &d[0] means as e is a pointer, so now e is pointing to the memory location of d[0] i.e. whatever changes e will make that changes will be reflected in d[0] similarly vice versa

*e = 20 means now location to which e is pointing will store value 20. Because earlier e was pointing to d[0] hence d[0] will contain 20

e[1] = 30, since e was pointing to d[0] hence e[1] will be pointing to d[1] . e[1] = 30 will make value of d[1] = 30

j = &d[1] means j will be an alias of d[1] . before this point j was an alias of i, after this point j will be alias of only d[1] i.e. d[1] and j will be practically same expect for the english spelling.

*j = i + d[1] as i was containing 50 (see above) and d[1] was containing 30 hence location of j will now contain 50+30 i.e. 80 but wait!! j was an alias of d[1] hence they are both practically same!!! hence d[1] will contain 80

printf(“d = [%d, %d]n”, d[0], d[1]); at this point d[0] has 20 and d[1] has 80 hence the output will be printed as I have shown.