18.08.2013 Views

Dalla A alla Z passando per C - Robotica

Dalla A alla Z passando per C - Robotica

Dalla A alla Z passando per C - Robotica

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Una implementazione di strlen, funzione che ritorna la lunghezza di una stringa, può quindi<br />

essere la seguente:<br />

int strlen(char *s)<br />

{<br />

char *t = s;<br />

for (; *t; t++)<br />

;<br />

return t - s;<br />

}<br />

8.4 Puntatori e strutture<br />

Una struttura dati può includerne altre o includere puntatori ad altre strutture. Mentre i puntatori<br />

possono riferire una struttura da un’altra ciclicamente, l’inclusione di strutture non può<br />

essere ricorsiva, <strong>per</strong>ché la struttura inclusa è interamente contenuta nella struttura includente.<br />

Poiché il compilatore effettua una sola passata sul codice, se una struttura contiene il puntatore<br />

ad un’altra struttura, occorre dichiarare tale struttura preventivamente, anche senza<br />

definirne l’elenco dei campi. Tale struttura non può essere istanziata, <strong>per</strong>ché il compilatore<br />

non sa la sua dimensione in byte, ma si possono definire puntatori ad essa, <strong>per</strong>ché i puntatori<br />

hanno tutti la stessa dimensione.<br />

Esempio:<br />

struct father;<br />

struct child {<br />

struct father *father;<br />

/* ... */<br />

};<br />

struct father {<br />

struct child *child;<br />

/* ... */<br />

};<br />

Dichiarare una struttura senza specificarne l’elenco dei campi <strong>per</strong>mette anche di creare strutture<br />

opache in una libreria, normalmente usate <strong>per</strong> dati privati della libreria stessa. Se una struttura<br />

contiene un puntatore <strong>alla</strong> struttura stessa non serve la dichiarazione preventiva, <strong>per</strong>ché mentre<br />

il compilatore legge la lista dei campi ha già visto il nome della struttura stessa.<br />

struct dpriv;<br />

struct datum {<br />

struct dpriv *priv; /* lista dei campi ignota all’utente di datum */<br />

/* ... */<br />

struct datum *next; /* <strong>per</strong> l’inserimento in una lista */<br />

};<br />

93

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!