Sistemi di Calcolo

Corso di Laurea in Ingegneria Informatica e Automatica - A.A. 2017-2018

HomePage | Avvisi | Diario lezioni | Programma | Materiale didattico | Esami | Forum | Login

Venerdì 13 ottobre 2017 (Lezione 4 - 90 min) - Demetrescu


Sessione pratica con spiegazioni:

Esempio 1: modifica i-esimo elemento di un array

main.c
#include <stdio.h>

void incr(short*, int);

int main() {
    short v[3] = { 3, 7, 17 };
    incr(v, 2);
    printf("%hd\n", v[2]); // stampa 18
    return 0;
}


incr.c
void incr(short* v, int i) {
    v[i]++;
}


incr.s
# void incr(short* v, int i) {
#     v[i]++;
# }

# void incr(short* v, int i) {
#     short* c = v; // indirizzo base vettore
#     int d = i;    // indice
#     short a = c[d];
#     a++;
#     c[d] = a;
# }

.globl incr

incr:
    movl 4(%esp), %ecx          # short* c = v; -> indirizzo base vettore
    movl 8(%esp), %edx          # int d = i;    -> indice
    movw (%ecx, %edx, 2), %eax  # short a = c[d];
    incw %ax                    # a++;
    movw %ax, (%ecx, %edx, 2)   # c[d] = a;
    ret


Esempio 2: scambio oggetti in memoria

main.c
#include <stdio.h>

void swap(char* x, char* y);

int main() {
    char u=10, v=20;
    swap(&u, &v);
    printf("u=%d, v=%d\n", u, v); // 20, 10
    return 0;
}


swap.c
void swap(char* x, char* y) {
    char a, c;
     a = *x;
     c = *y;
    *y =  a;
    *x =  c;
}


swap.s
# void swap(char* x, char* y) {
#     char a, c;
#      a = *x;
#      c = *y;
#     *y =  a;
#     *x =  c;
# }

# void swap(char* x, char* y) {
#     char a, c, *d;
#      d =  x;
#      a = *d; //  a = *x
#      d =  y;
#      c = *d; //  c = *y
#     *d =  a; // *y =  a
#      d =  x;
#     *d =  c; // *x =  c
# }

.globl swap

swap:
    movl 4(%esp), %edx   #  d =  x;
    movb (%edx), %al     #  a = *d; ->  a = *x
    movl 8(%esp), %edx   #  d =  y;
    movb (%edx), %cl     #  c = *d; ->  c = *y
    movb %al, (%edx)     # *d =  a; -> *y =  a
    movl 4(%esp), %edx   #  d =  x;
    movb %cl, (%edx     )# *d =  c; -> *x =  c
    ret

Valid XHTML 1.0 Transitional :: Valid CSS :: Powered by WikkaWiki
Page was generated in 0.0599 seconds