tags:

views:

90

answers:

1

Hi, I'd like to know if someone can explain me the solution to this problem:

the code is:

#include <stdio.h> 
#include <stdlib.h> 
typedef struct { 
    int c[20]; 
    int n; 
} t_coda; 
t_coda coda; 
void init(t_coda *coda) { 
    coda->n = 0; 
} 
void add(t_coda *coda, int x) { 
    if (coda->n < 20) 
        coda->c[(coda->n)++] = x; 
} 
main() { 
    init(&coda); 
    coda->n=1; 
    coda->c[0]=2; 
    add(&coda,3); 
    add(&coda,4); 
} 

And I need to know the corresponding instruction of: coda->n = 0; and coda->c[(coda->n)++] = x; in simplesem (an assembly-like semantic);

The solution is:

set D[D[0]+3]+20, 0 

for the first question and:

set D[D[0]+3]+D[D[D[0]+3]+20], D[D[0]+4]
set D[D[0]+3]+20, D[D[D[0]+3]+20] + 1

for the second one;

D is the Data stack, and D[0] return the value contained in the 0-cell of the data

Thank you

+1  A: 

I would guess that...

  • D[0]+3 is a reference to the address of coda (the *coda in the function call)
  • D[D[0]+3] is a lookup of the data at the address where coda is stored
  • D[D[0]+3]+20 is an offset of 20 from where coda begins, thus moving past coda->c (which is 20 items) to get to coda->n.

That should help you to understand the first one; the same ideas can be extended to the second.

Amber